如何在Flutter中使用Riverpod和日期范围选择器

huangapple go评论64阅读模式
英文:

How to use Flutter Riverpod with Date Range Picker

问题

我正在尝试将Flutter Riverpod与日期范围选择器一起使用。

  • 我有一个Trips列表,当单击时,会打开Trip Page

如何在Flutter中使用Riverpod和日期范围选择器

  • 在Trip页面上,用户可以查看开始/结束日期。

如何在Flutter中使用Riverpod和日期范围选择器

  • 然后,他们可以单击一个按钮,打开日期范围选择器小部件。

如何在Flutter中使用Riverpod和日期范围选择器

  • 我希望用户能够更改日期范围,并在屏幕上反映出来(最终保存到Trip对象中)。
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(
    const ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Riverpod DateRange Picker',
      home: HomeScreen(),
    );
  }
}

class Trip {
  final String name;
  final DateTimeRange dateTimeRange;
  Trip(this.name, this.dateTimeRange);
}

class HomeScreen extends ConsumerWidget {
  const HomeScreen({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    Set<Trip> trips = {
      Trip('Test 1',
          DateTimeRange(start: DateTime(2023, 1, 3), end: DateTime(2023, 1, 6)))
    };
    return Scaffold(
      appBar: AppBar(title: const Text('Riverpod DateRange Picker')),
      body: ListView(
        children: [
          for (final trip in trips)
            ListTile(
              title: Text(trip.name),
              onTap: () {
                Navigator.push(
                    context,
                    MaterialPageRoute<void>(
                        builder: (BuildContext context) =>
                            TripScreen(trip: trip)));
              },
            ),
        ],
      ),
    );
  }
}

class TripScreen extends ConsumerWidget {
  const TripScreen({Key? key, required this.trip}) : super(key: key);

  final Trip trip;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    void _showDateRangePicker() async {
      final DateTimeRange? result = await showDateRangePicker(
        context: context,
        locale: const Locale('en', 'GB'),
        initialDateRange: trip.dateTimeRange,
        saveText: 'Done',
        firstDate: DateTime(2022, 1, 1),
        lastDate: DateTime(2030, 12, 31),
      );

      if (result != null) {
        print(result);
      }
    }

    return WillPopScope(
        onWillPop: () {
          Navigator.pop(context);
          return Future.value(false);
        },
        child: Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              title: Text(trip.name),
            ),
            body: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    IconButton(
                      icon: const Icon(Icons.calendar_month),
                      onPressed: () {
                        _showDateRangePicker();
                      },
                    ),
                    Text(
                        'Start: ${DateFormat('dd/MM/yyyy').format(trip.dateTimeRange.start)}'),
                    Text(
                        'End: ${DateFormat('dd/MM/yyyy').format(trip.dateTimeRange.end)}'),
                  ],
                ))));
  }
}

任何帮助将不胜感激。

谢谢。

我已经使用Provider创建了这个,但我想使用Riverpod。

英文:

I am trying to use Flutter Riverpod together with the Date Range Picker.

  • I have a list of Trips which when clicked on, open up the Trip Page.

如何在Flutter中使用Riverpod和日期范围选择器

  • On the trip page, the user can view the start / end dates

如何在Flutter中使用Riverpod和日期范围选择器

  • They can then click on a button, which brings up the Date Range Picker widget

如何在Flutter中使用Riverpod和日期范围选择器

  • I want the user to be able to change the date range, and this be reflected on the screen (and eventually saved back against the Trip object)
import &#39;package:flutter/material.dart&#39;;
import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;
import &#39;package:intl/intl.dart&#39;;
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: &#39;Riverpod DateRange Picker&#39;,
home: HomeScreen(),
);
}
}
class Trip {
final String name;
final DateTimeRange dateTimeRange;
Trip(this.name, this.dateTimeRange);
}
class HomeScreen extends ConsumerWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
Set&lt;Trip&gt; trips = {
Trip(&#39;Test 1&#39;,
DateTimeRange(start: DateTime(2023, 1, 3), end: DateTime(2023, 1, 6)))
};
return Scaffold(
appBar: AppBar(title: const Text(&#39;Riverpod DateRange Picker&#39;)),
body: ListView(
children: [
for (final trip in trips)
ListTile(
title: Text(trip.name),
onTap: () {
Navigator.push(
context,
MaterialPageRoute&lt;void&gt;(
builder: (BuildContext context) =&gt;
TripScreen(trip: trip)));
},
),
],
),
);
}
}
class TripScreen extends ConsumerWidget {
const TripScreen({Key? key, required this.trip}) : super(key: key);
final Trip trip;
@override
Widget build(BuildContext context, WidgetRef ref) {
void _showDateRangePicker() async {
final DateTimeRange? result = await showDateRangePicker(
context: context,
locale: const Locale(&#39;en&#39;, &#39;GB&#39;),
initialDateRange: trip.dateTimeRange,
saveText: &#39;Done&#39;,
firstDate: DateTime(2022, 1, 1),
lastDate: DateTime(2030, 12, 31),
);
if (result != null) {
print(result);
}
}
return WillPopScope(
onWillPop: () {
Navigator.pop(context);
return Future.value(false);
},
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(trip.name),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: &lt;Widget&gt;[
IconButton(
icon: const Icon(Icons.calendar_month),
onPressed: () {
_showDateRangePicker();
},
),
Text(
&#39;Start: ${DateFormat(&#39;dd/MM/yyyy&#39;).format(trip.dateTimeRange.start)}&#39;),
Text(
&#39;End: ${DateFormat(&#39;dd/MM/yyyy&#39;).format(trip.dateTimeRange.end)}&#39;),
],
))));
}
}

Any help would be much appriciated.

Thanks.

I've created this using Provider but I would like to use Riverpod.

答案1

得分: 1

我创建了一个 "tripsProvider" 实例,它是 StateProvider 的实例,用于保存所有的旅行数据,就像在你的情况下只有一个值。主屏幕观察该提供程序并在 ListView 中显示数据,当用户在列表中选择项目时,我传递项目的索引,并在新屏幕上(与你的 TripScreen 类似的屏幕副本)观察该单个项目。当用户更新单个项目的数据时,我更新了列表,因此在 TripScreen 和 HomeScreen 上都可以看到更新。我仍在学习 riverpod,但希望我的答案能帮到你。

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(
    const ProviderScope(
      child: MyApp(),
    ),
  );
}

final tripsProvider = StateProvider<List<Trip>>(
  (ref) => [
    Trip(
      'Test 1',
      DateTimeRange(start: DateTime(2023, 1, 3), end: DateTime(2023, 1, 6)),
    ),
  ],
);

class Trip {
  final String name;
  final DateTimeRange dateTimeRange;

  const Trip(this.name, this.dateTimeRange);
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Riverpod DateRange Picker',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends ConsumerWidget {
  const HomeScreen({Key? key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final trips = ref.watch(tripsProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('Riverpod DateRange Picker')),
      body: ListView.builder(
        itemCount: trips.length,
        itemBuilder: (context, index) {
          Trip trip = trips[index];

          return ListTile(
            title: Text(trip.name),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute<void>(
                  builder: (BuildContext context) => TripScreen(index: index),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class TripScreen extends ConsumerWidget {
  int index;

  TripScreen({Key? key, required this.index}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final trip = ref.watch(tripsProvider)[index];

    void _showDateRangePicker() async {
      final DateTimeRange? result = await showDateRangePicker(
        context: context,
        locale: const Locale('en', 'GB'),
        initialDateRange: trip.dateTimeRange,
        saveText: 'Done',
        firstDate: DateTime(2022, 1, 1),
        lastDate: DateTime(2030, 12, 31),
      );

      if (result != null) {
        print(result);
        Trip updatedTrip = Trip(trip.name, DateTimeRange(start: result.start, end: result.end));

        ref.read(tripsProvider.notifier).update(
          (state) {
            List<Trip> updatedList = [];
            for (int i = 0; i < state.length; i++) {
              if (i == index) {
                updatedList.add(updatedTrip);
              } else {
                updatedList.add(state[i]);
              }
            }
            return updatedList;
          },
        );
      }
    }

    return WillPopScope(
      onWillPop: () {
        Navigator.pop(context);
        return Future.value(false);
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text(trip.name),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              IconButton(
                icon: const Icon(Icons.calendar_month),
                onPressed: () {
                  _showDateRangePicker();
                },
              ),
              Text('Start: ${DateFormat('dd/MM/yyyy').format(trip.dateTimeRange.start)}'),
              Text('End: ${DateFormat('dd/MM/yyyy').format(trip.dateTimeRange.end)}'),
            ],
          ),
        ),
      ),
    );
  }
}
英文:

I created "tripsProvider" instance of StateProvider that holds all trip data, like in your case only one value. Home screen watching that provider and displaying data in ListView, when user select item in list I pass index of item and watch that single item on new screen (copy of yours TripScreen).
When user update the data of single item I update that list, so update is available on TripScreen and HomeScreen. I also still learning riverpod but hope my answer can help you.

import &#39;package:flutter/material.dart&#39;;
import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;
import &#39;package:intl/intl.dart&#39;;
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
final tripsProvider = StateProvider&lt;List&lt;Trip&gt;&gt;(
(ref) =&gt; [
Trip(
&#39;Test 1&#39;,
DateTimeRange(start: DateTime(2023, 1, 3), end: DateTime(2023, 1, 6)),
),
],
);
class Trip {
final String name;
final DateTimeRange dateTimeRange;
const Trip(this.name, this.dateTimeRange);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: &#39;Riverpod DateRange Picker&#39;,
home: HomeScreen(),
);
}
}
class HomeScreen extends ConsumerWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final trips = ref.watch(tripsProvider);
return Scaffold(
appBar: AppBar(title: const Text(&#39;Riverpod DateRange Picker&#39;)),
body: ListView.builder(
itemCount: trips.length,
itemBuilder: (context, index) {
Trip trip = trips[index];
return ListTile(
title: Text(trip.name),
onTap: () {
Navigator.push(
context,
MaterialPageRoute&lt;void&gt;(
builder: (BuildContext context) =&gt; TripScreen(index: index),
),
);
},
);
},
),
);
}
}
class TripScreen extends ConsumerWidget {
int index;
TripScreen({Key? key, required this.index}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final trip = ref.watch(tripsProvider)[index];
void _showDateRangePicker() async {
final DateTimeRange? result = await showDateRangePicker(
context: context,
locale: const Locale(&#39;en&#39;, &#39;GB&#39;),
initialDateRange: trip.dateTimeRange,
saveText: &#39;Done&#39;,
firstDate: DateTime(2022, 1, 1),
lastDate: DateTime(2030, 12, 31),
);
if (result != null) {
print(result);
Trip updatedTrip = Trip(trip.name, DateTimeRange(start: result.start, end: result.end));
ref.read(tripsProvider.notifier).update(
(state) {
List&lt;Trip&gt; updatedList = [];
for (int i = 0; i &lt; state.length; i++) {
if (i == index) {
updatedList.add(updatedTrip);
} else {
updatedList.add(state[i]);
}
}
return updatedList;
},
);
}
}
return WillPopScope(
onWillPop: () {
Navigator.pop(context);
return Future.value(false);
},
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(trip.name),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: &lt;Widget&gt;[
IconButton(
icon: const Icon(Icons.calendar_month),
onPressed: () {
_showDateRangePicker();
},
),
Text(&#39;Start: ${DateFormat(&#39;dd/MM/yyyy&#39;).format(trip.dateTimeRange.start)}&#39;),
Text(&#39;End: ${DateFormat(&#39;dd/MM/yyyy&#39;).format(trip.dateTimeRange.end)}&#39;),
],
),
),
),
);
}
}

huangapple
  • 本文由 发表于 2023年2月10日 05:53:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定