liuyuqi-dellpc 1 year ago
parent
commit
46ffbc6935

+ 10 - 0
README.md

@@ -7,3 +7,13 @@ provider 状态管理demo
 ```
 flutter build apk
 ```
+
+
+## 说明
+
+1、导入 provider包
+2、main.dart中添加 MultiProvider
+3、创建model层,proveder层的ChangeNotifier类
+
+## 参考
+

+ 10 - 0
lib/dao/car_dao.dart

@@ -6,6 +6,16 @@ class CarDao {
     return [
       CarModel(id: 1, brand: "大众", type: "朗逸"),
       CarModel(id: 2, brand: "大众", type: "帕萨特"),
+      CarModel(id: 3, brand: "大众", type: "迈腾"),
+      CarModel(id: 4, brand: "大众", type: "途观", start: true),
+      CarModel(id: 5, brand: "大众", type: "途昂"),
+      CarModel(id: 6, brand: "大众", type: "途岳", start: true),
+      CarModel(id: 7, brand: "大众", type: "途铠"),
+      CarModel(id: 8, brand: "大众", type: "途锐", start: true),
+      CarModel(id: 9, brand: "大众", type: "途昂X"),
+      CarModel(id: 10, brand: "大众", type: "途岳X", start: true),
+      CarModel(id: 11, brand: "大众", type: "途铠X"),
+      CarModel(id: 12, brand: "大众", type: "途观L"),
     ];
   }
 

+ 13 - 11
lib/pages/addpage_page.dart

@@ -22,13 +22,14 @@ class _AddcardPageState extends State<AddcardPage> {
   Widget build(BuildContext context) {
     return Scaffold(
       appBar: AppBar(
-        actions: [],
-        title: Text("增加车辆"),
+        actions: const [],
+        title: const Text("增加车辆"),
       ),
       body: ListView(children: [
         Padding(
-          padding: EdgeInsets.all(25),
+          padding: const EdgeInsets.all(25),
           child: Column(
+            crossAxisAlignment: CrossAxisAlignment.stretch,
             children: [
               TextField(
                 controller: carBrandController,
@@ -40,20 +41,21 @@ class _AddcardPageState extends State<AddcardPage> {
                 value: started,
                 onChanged: (checked) {
                   setState(() {
-                    started = checked;
+                    started = checked ?? false;
                   });
                 },
                 title: const Text('Start ?'),
               ),
-              RaisedButton(
-                elevation: 5.0,
-                child: Text('Add'),
-                onPressed: onAdd,
-                shape: RoundedRectangleBorder(
-                    borderRadius: BorderRadius.circular(30.0)),
+              ElevatedButton(
+                onPressed: () {
+                  addCar(1);
+                },
+                style: ElevatedButton.styleFrom(
+                    backgroundColor: Colors.blue,
+                    textStyle: const TextStyle(fontSize: 20)),
+                child: const Text('Add'),
               ),
             ],
-            crossAxisAlignment: CrossAxisAlignment.stretch,
           ),
         )
       ]),

+ 62 - 13
lib/pages/home_page.dart

@@ -1,27 +1,76 @@
 import 'package:flutter/material.dart';
-import 'package:flutter_provider_demo/routes.dart';
+import 'package:flutter_provider_demo/pages/addpage_page.dart';
+import 'package:flutter_provider_demo/provider/car_provider.dart';
+import 'package:flutter_provider_demo/views/all_cars.dart';
+import 'package:flutter_provider_demo/views/ready_cars.dart';
+import 'package:flutter_provider_demo/views/unready_cars.dart';
+import 'package:provider/provider.dart';
 
 /// Description: home page
 /// Time       : 09/03/2023 Sunday
 /// Author     : liuyuqi.gov@msn.cn
-class MyWidget extends StatefulWidget {
-  const MyWidget({super.key});
+class HomePage extends StatefulWidget {
+  const HomePage({super.key});
+  static bool hasData = false;
 
   @override
-  State<MyWidget> createState() => _MyWidgetState();
+  State<HomePage> createState() => _HomePageState();
 }
 
-class _MyWidgetState extends State<MyWidget> {
+class _HomePageState extends State<HomePage>
+    with SingleTickerProviderStateMixin {
+  late TabController tabController;
+
+  @override
+  void initState() {
+    super.initState();
+    tabController = TabController(length: 3, vsync: this);
+  }
+
   @override
   Widget build(BuildContext context) {
-    return const Scaffold(
-      appBar: AppBar(actions: [
-        IconButton(icon: Icon(Icons.add), onPressed: () {
-          Navigator.pushNamed(context, Routes.carAdd);
-        }),
-        }),
-      ], title: Text('汽车列表'),),
-      ], title: Text('汽车列表'),'))]),
+    Provider.of<CarProvider>(context).getCars();
+
+    if (Provider.of<CarProvider>(context).count > 0) {
+      HomePage.hasData = true;
+    }
+
+    return Scaffold(
+      appBar: AppBar(
+        title: const Text('Your Cars'),
+        actions: <Widget>[
+          IconButton(
+            icon: const Icon(Icons.add),
+            onPressed: () {
+              Navigator.of(context).push(
+                  MaterialPageRoute(builder: (context) => const AddcardPage()));
+            },
+          ),
+        ],
+        bottom: TabBar(
+          controller: tabController,
+          tabs: const <Widget>[
+            Tab(text: 'UnReady'),
+            Tab(text: 'All'),
+            Tab(text: 'Ready'),
+          ],
+        ),
+      ),
+      body: Provider.of<CarProvider>(context).count > 0
+          ? TabBarView(
+              controller: tabController,
+              children: const <Widget>[
+                AllCarsTab(),
+                UnReadyCarsTab(),
+                ReadyCarsTab()
+              ],
+            )
+          : const Center(
+              child: Text(
+                '',
+                style: TextStyle(fontSize: 20.0),
+              ),
+            ),
     );
   }
 }

+ 15 - 0
lib/provider/car_provider.dart

@@ -1,3 +1,5 @@
+import 'dart:collection';
+
 import 'package:flutter/material.dart';
 import 'package:flutter_provider_demo/dao/car_dao.dart';
 import 'package:flutter_provider_demo/model/car_model.dart';
@@ -9,6 +11,15 @@ class CarProvider extends ChangeNotifier {
   late List<CarModel> _cars;
   int _count = 0;
 
+  int get count => _count;
+  UnmodifiableListView<CarModel> get allCars => UnmodifiableListView(_cars);
+
+  UnmodifiableListView<CarModel> get unStartedCars =>
+      UnmodifiableListView(_cars.where((car) => car.start == false));
+
+  UnmodifiableListView<CarModel> get startedCars =>
+      UnmodifiableListView(_cars.where((car) => car.start == true));
+
   Future<List<CarModel>> getCars() async {
     _cars = await CarDao.getCars();
     notifyListeners();
@@ -41,4 +52,8 @@ class CarProvider extends ChangeNotifier {
     );
     ScaffoldMessenger.of(context).showSnackBar(snackBar);
   }
+
+  void startCar(BuildContext context, CarModel car) {
+    notifyListeners();
+  }
 }

+ 1 - 0
lib/routes.dart

@@ -1,5 +1,6 @@
 import 'package:flutter/material.dart';
 import 'package:flutter_provider_demo/index_page.dart';
+import 'package:flutter_provider_demo/pages/addpage_page.dart';
 
 /// Description: routes
 /// Time       : 09/03/2023 Sunday

+ 29 - 0
lib/views/all_cars.dart

@@ -0,0 +1,29 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_provider_demo/provider/car_provider.dart';
+import 'package:flutter_provider_demo/views/carlist.dart';
+import 'package:provider/provider.dart';
+
+/// Description:
+/// Time       : 09/04/2023 Monday
+/// Author     : liuyuqi.gov@msn.cn
+class AllCarsTab extends StatelessWidget {
+  const AllCarsTab({super.key});
+
+  @override
+  Widget build(BuildContext context) {
+    return Consumer<CarProvider>(
+      builder: (context, cars, _) => cars.allCars.isNotEmpty
+          ? CarList(
+              cars: cars.allCars,
+            )
+          : const Center(
+              child: Text(
+                'There are no cars',
+                style: TextStyle(
+                  fontSize: 25.0,
+                ),
+              ),
+            ),
+    );
+  }
+}

+ 55 - 0
lib/views/carlist.dart

@@ -0,0 +1,55 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_provider_demo/model/car_model.dart';
+import 'package:flutter_provider_demo/provider/car_provider.dart';
+import 'package:provider/provider.dart';
+
+class CarList extends StatelessWidget {
+  final List<CarModel> cars;
+
+  const CarList({super.key, required this.cars});
+
+  @override
+  Widget build(BuildContext context) {
+    return ListView(
+      children: getChildrenCars(),
+    );
+  }
+
+  List<CarListItem> getChildrenCars() {
+    return cars
+        .map((car) => CarListItem(
+              car: car,
+            ))
+        .toList();
+  }
+}
+
+class CarListItem extends StatelessWidget {
+  final CarModel car;
+
+  const CarListItem({super.key, required this.car});
+
+  @override
+  Widget build(BuildContext context) {
+    return ListTile(
+      leading: Checkbox(
+        value: car.start,
+        onChanged: (bool? value) {
+          Provider.of<CarProvider>(context, listen: false)
+              .startCar(context, car);
+        },
+      ),
+      title: Text("${car.brand}  ${car.type}"),
+      trailing: IconButton(
+        onPressed: () {
+          Provider.of<CarProvider>(context, listen: false)
+              .deleteCar(context, car);
+        },
+        icon: Icon(
+          Icons.delete,
+          color: Theme.of(context).colorScheme.secondary,
+        ),
+      ),
+    );
+  }
+}

+ 27 - 0
lib/views/ready_cars.dart

@@ -0,0 +1,27 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_provider_demo/provider/car_provider.dart';
+import 'package:flutter_provider_demo/views/carlist.dart';
+
+import 'package:provider/provider.dart';
+
+class ReadyCarsTab extends StatelessWidget {
+  const ReadyCarsTab({super.key});
+
+  @override
+  Widget build(BuildContext context) {
+    return Consumer<CarProvider>(
+      builder: (context, cars, _) => cars.startedCars.isNotEmpty
+          ? CarList(
+              cars: cars.startedCars,
+            )
+          : const Center(
+              child: Text(
+                'There are no ready cars',
+                style: TextStyle(
+                  fontSize: 25.0,
+                ),
+              ),
+            ),
+    );
+  }
+}

+ 27 - 0
lib/views/unready_cars.dart

@@ -0,0 +1,27 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_provider_demo/provider/car_provider.dart';
+import 'package:flutter_provider_demo/views/carlist.dart';
+
+import 'package:provider/provider.dart';
+
+class UnReadyCarsTab extends StatelessWidget {
+  const UnReadyCarsTab({super.key});
+
+  @override
+  Widget build(BuildContext context) {
+    return Consumer<CarProvider>(
+      builder: (context, cars, _) => cars.unStartedCars.isNotEmpty
+          ? CarList(
+              cars: cars.unStartedCars,
+            )
+          : const Center(
+              child: Text(
+                'There are no incomplete tasks',
+                style: TextStyle(
+                  fontSize: 25.0,
+                ),
+              ),
+            ),
+    );
+  }
+}