如何用提供者的价值更新其他页面?

时间:2020-10-16 20:37:41

标签: android flutter dart provider

如何使用主选项卡页中提供的提供程序值来更新另一页?使用提供程序将进度值传递到第二个选项卡。 secondtab无法更新。怎么了?什么可以纠正?

这是main.dart文件:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ShareProgress>(
      create: (_) => ShareProgress(),
      child: MaterialApp(
        title: 'VideoTube',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          accentColor: Colors.red[400]
        ),
        debugShowCheckedModeBanner: false,
        home: App(),
      ),
    );
  }
}

这是ShareProgress.dart文件:

class ShareProgress extends ChangeNotifier {
  int _progress = 0;

  

  void setprogress(int newProgress) {
    _progress = newProgress;

    notifyListeners();
  }

  int get progress => _progress;
}

这是主标签:

onReceiveProgress: (count, total) {
        var percentage = count / total * 100;

        

        ShareProgress().setprogress(count);
        setState(() {
          downloadMessage = 'downloadin.... ${percentage.floor()}%';
          

         // print(downloadMessage);
        });
        ShareProgress().setprogress(count);
      },

这是第二个标签:

class _SecondTabState extends State<SecondTab> {
  @override
  Widget build(BuildContext context) {
    final progress = Provider.of<ShareProgress>(context);
    print(progress.progress);
    return Container(
      child: Text('second ${progress.progress}'),
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您必须使用Cunsumer来重建您的小部件:

class _SecondTabState extends State<SecondTab> {
  @override
  Widget build(BuildContext context) {
    return Consumer<KeyboardNotifier>(
            builder: (context, value, _) => Container(
               child: Text('second ${value.progress}'),
      ),
    );
  }
}