美文网首页
flutter provider

flutter provider

作者: f8d1cf28626a | 来源:发表于2022-11-26 07:34 被阅读0次

Provider 状态管理的使用

导入 provider: ^6.0.4

  • ChangeNotifier
  • ChangeNotifierProvider
  • Provider.of<>
  1. 简单使用

案例1

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// 管理监听者(通知模式)注意:需要将此数据放到根节点的widget
class NumberModel with ChangeNotifier {
  int _count = 0;
  // 对外暴露的数据
  int get getNumber => _count;
  void incrementing(){
    _count += 1;
    // 相当于ios notification 
    notifyListeners();
  }
}

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return ChangeNotifierProvider.value(
      value: NumberModel(), // 自定义的通知模型
      child: MaterialApp(
        title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const ProviderPage1(),
      ),
    );
  }

}

// 第一个页面
class ProviderPage1 extends StatelessWidget {
  const ProviderPage1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final notify = Provider.of<NumberModel>(context);

    return Scaffold(
      appBar: AppBar(title: const Text('1'),),
      body: Center(child: Text('壹 count: ${notify.getNumber}'),),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
          onPressed: (){
          Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){
            return const ProviderPage2();
          }));
          }),
    );
  }
}

// 第二个页面
class ProviderPage2 extends StatelessWidget {
  const ProviderPage2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final notify = Provider.of<NumberModel>(context);

    return Scaffold(
      appBar: AppBar(title: const Text('2'),),
      body: Center(child: Text('贰 count: ${notify.getNumber}'),),
      floatingActionButton: FloatingActionButton(
          child: const Icon(Icons.next_plan),
          onPressed: (){
            debugPrint(' c p p ');
            notify.incrementing();
          }),
    );
  }
}

注意:以上的操作将整个页面全部都刷新了一遍(不够细,不够到位)

  1. 精确使用

案例2 做到哪里更新数据就只渲染改变位置的widget

  • Consumer(child: _,builder: (fContext,NumberModel model,child) => Text('壹 count: ${model.getNumber}'))

注意:child 是不被刷新的widget,因为只需要刷新Text,让builder精确到每一个widget,与数据刷新无关的widget不需要重新渲染


void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return ChangeNotifierProvider.value(
      value: NumberModel(), // 自定义的通知模型
      child: MaterialApp(
        title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const ProviderPage1(),
      ),
    );
  }
}

// 第一个页面
class ProviderPage1 extends StatelessWidget {
  const ProviderPage1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: const Text('1'),),
      body: Center(child: Consumer(builder: (fContext,NumberModel model,_){
        return Text('壹 count: ${model.getNumber}');
      }),),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
          onPressed: (){
          Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){
            return const ProviderPage2();
          }));
          }),
    );
  }
}

// 第二个页面
class ProviderPage2 extends StatelessWidget {
  const ProviderPage2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: const Text('2'),),
      body: Center(child: Consumer(builder: (contex1,NumberModel model,_){
        return Text('贰 count: ${model.getNumber}');
      })),
      floatingActionButton: Consumer(
        child: const Icon(Icons.luggage),
        builder: (contex2,NumberModel model,child){
          return FloatingActionButton(child: child,onPressed: () => model.incrementing());
        },
      ),
    );
  }
}

provider

临时目录
getTemporaryDirectory

文档目录
getApplicationDocumentsDirectory

sd卡目录
getExternalStorageDirectory

新增文件、读取文件

  /**
  * 加载文件
  * async 异步
  */
 localPath() async {
   try {
     //得到临时目录
     var tempDir = await getTemporaryDirectory();
     String tempPath = tempDir.path;

     //文档目录
     var appDorDir = await getApplicationDocumentsDirectory();
     String appDocPath = appDorDir.path;

     //sd卡目录
     var sdDir = await getExternalStorageDirectory();
     String sdPaht = sdDir.path;


     print('临时目录' + tempPath);
     print('文档目录' + appDocPath);
     print('sd卡目录' + sdPaht);

     ////文件的读写操作
     Directory(appDocPath + "/我的文件1/" + "txt文件").create(
         recursive: true).then((Directory d) {
       return new File(d.path + "/" + "1.txt").create(recursive: true).then((
           File file) {
         file.writeAsString('往缓存文件中加入数据2').then((File file) {
           //当写完数据后才能读取
           file.readAsString().then((String data) {
             print('数据是:$data');
           });
         });
       });
     });
   } catch (e) {
     print(e);
   }
 }

删除文件

 //文件的删除操作
     Directory(appDocPath + "/我的文件1/" + "txt文件").delete(recursive: true).then((
         FileSystemEntity fileSystemEntity) {
       print('删除path' + fileSystemEntity.path);
     });
   } catch (e) {
     print(e);
   }

相关文章

网友评论

      本文标题:flutter provider

      本文链接:https://www.haomeiwen.com/subject/ltoqfdtx.html