如何在多个有状态小部件(父级和兄弟级)之间共享公共提供程序?

时间:2019-09-20 09:28:05

标签: flutter dart flutter-layout

我是扑扑和提供者的新手。我处于主屏幕(全状态小部件) 网页浏览为子级(脚手架)。页面浏览的所有子级也都是全状态的小部件,并且有一个Fab打开底页,这也是全状态的小部件。

在我的情况下,底部表格显示了一些设置,假设一个单选按钮更改了提供程序类的值(是或否)

现在,我希望如果从底部更改了无线电值,则必须通知所有页面浏览的子级并更新其内容

我该如何通过提供者来实现? 主屏幕应该是提供者的子对象,然后将该对象传递给其子对象,还是所有子对象都应该是提供者的子对象?

以下是代码:

1 Main.dart

import 'package:flutter/material.dart';
import 'package:providerdemo/mypage.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return MaterialApp(
    home: MainScreen(),
    );
}
}

class MainScreen extends StatefulWidget {

@override
_MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {

void _modalBottomSheetMenu() {
    showModalBottomSheet(
    context: context,
    builder: (builder) {
        return MyBottomSheet;
    },
    );
}

@override
Widget build(BuildContext context) {
    return Scaffold(
    body: PageView(
        scrollDirection: Axis.horizontal,
        children: <Widget>[
        MyPage(),
        MyPage(),
        ],
    ),
    floatingActionButton: FloatingActionButton(
        child: Icon(Icons.arrow_upward),
        onPressed: _modalBottomSheetMenu,
    ),
    );
}
}

2 myprovider

import 'package:flutter/material.dart';

class MyProvider with ChangeNotifier {
bool _isEnabled = false;

bool get isEnabled => _isEnabled;

setData(bool newvalue) {
    _isEnabled = newvalue;
    notifyListeners();
}
}

3个mybottomsheet

import 'package:flutter/material.dart';

class MyBottomSheet extends StatefulWidget {
@override
_MyBottomSheetState createState() => _MyBottomSheetState();
}

class _MyBottomSheetState extends State<MyBottomSheet> {
@override
Widget build(BuildContext context) {
    return Center(
    child: Switch(
        onChanged: (newval){
        //here i want to make change in my provider file which needs to be reflected in pageview
        },
        value: true,
    ),
    );
}
}

4个我的页面

import 'package:flutter/material.dart';

class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
@override
Widget build(BuildContext context) {
    return Container(
    child: Text("Here I want to know the bool value from provider"),
    );
}
}

0 个答案:

没有答案