flutter : 공급자가 statefulwidget에서 작동하지 않습니다.

mrd2242

새 flutter 데모를 만들고 공급자 패키지를 사용하도록 수정합니다. 하지만 작동하지 않습니다. 그리고 여기에 내 코드가 있습니다.

class MyState {
  MyState();
  int cnt = 0;
  void increase() {
    print("increase. $cnt");
    cnt++;
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Provider<MyState>(
        create: (_) => MyState(),
        child: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Consumer<MyState>(
              builder: (context, state, _) {
                return Text(
                  "${state.cnt}",
                  style: Theme.of(context).textTheme.headline4,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: Provider.of<MyState>(context, listen: false).increase,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

버튼을 눌러도 UI가 재 구축되지 않습니다. 그리고 인쇄 된 메시지에서 알 수 있듯이 Mystate의 cnt 필드가 변경되었습니다. 왜? statefulwidget에서 provider를 사용할 수 없습니까?

Shubham narkhede

Provider : Provider를 사용하여 위젯 트리의 모든 위치에 값을 제공 할 수 있습니다. 값이 변경 될 때마다 위젯 트리를 다시 빌드하지 않습니다. 단순히 모델을 위젯 트리의 하위 위젯에 전달합니다.

ChangeNotifierProvider : ChangeNotifierProvider는 모델 객체의 변경 사항을 수신합니다. ChangeNotifier.notifyListeners 가 호출 될 때마다 종속 위젯을 다시 빌드합니다 .

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyState with ChangeNotifier {
  MyState();

  int cnt = 0;

  void increase() {
    print("increase. $cnt");
    cnt++;
    notifyListeners();
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MyState>(
      create: (context) => MyState(),
      child: Scaffold(
        appBar: AppBar(
          title: Text("Page Title"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'You have pushed the button this many times:',
              ),
              Consumer<MyState>(
                builder: (context, counter, child) => Text(
                  '${counter.cnt}',
                  style: Theme.of(context).textTheme.display1,
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: Builder(builder: (context) {
          return FloatingActionButton(
            onPressed: Provider.of<MyState>(context, listen: false).increase,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          );
        }),
      ),
    );
  }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

View :: composer가 boot () 서비스 공급자에서 작동하지 않습니다.

분류에서Dev

DotNetOpenAuth 공급자가 https의 IE11에서 작동하지 않습니다.

분류에서Dev

Flutter Firestore getDocuments ()가 initState에서 작동하지 않습니다.

분류에서Dev

setState ()가 flutter에서 제대로 작동하지 않습니다.

분류에서Dev

Flutter Firebase Auth가 Google Play에서 작동하지 않습니다.

분류에서Dev

Flutter hot reload가 VSCode의 자동 저장에서 작동하지 않습니다.

분류에서Dev

EF 캐싱 공급자 래퍼가 EF 6.0.2에서 작동하지 않습니다.

분류에서Dev

Flutter 제공자가 notifyListeners에 응답하지 않습니다

분류에서Dev

Navigator.push가 flutter에서 setState와 함께 작동하지 않습니다.

분류에서Dev

Flutter의 Align 위젯에서 onTap 함수가 작동하지 않습니다.

분류에서Dev

Row ()의 컨테이너가 Flutter에서 작동하지 않습니다.

분류에서Dev

Flutter의 PayPal WebView가 물리적 장치에서 작동하지 않습니다.

분류에서Dev

Angular 2 공급자가 useValue 및 new에 대한 함수 호출과 함께 작동하지 않습니다.

분류에서Dev

검색 사용자가 Flutter에서 작동하지 않습니다. 어떻게 해결합니까?

분류에서Dev

Flutter async / await가 2 개의 Firebase 함수간에 작동하지 않습니다.

분류에서Dev

StaggeredGridView의 동적 높이가 flutter 프로젝트에서 작동하지 않습니다.

분류에서Dev

'flutter pub get'이 VSCode에서 작동하지 않습니다.

분류에서Dev

Angular 8 Resolver가 작동하지 않음 : Resolver에 대한 공급자 없음

분류에서Dev

Flutter 공급자가 UI를 업데이트하지 않음

분류에서Dev

Flutter에서 List의 ADD 메서드가 작동하지 않습니다 (List.add ()).

분류에서Dev

Dart / Flutter WebSocket 서버 / 클라이언트가 같은 쪽에서 제대로 작동하지 않습니다.

분류에서Dev

Flutter TikTokStyleFullPageScroller ()가 비어있는 (콘텐츠가 아닌) 화면에서 작동하지 않습니다.

분류에서Dev

C ++ 문자열에서 공백 제거가 작동하지 않습니다.

분류에서Dev

Firebase Phone Auth가 iOS 시뮬레이터 나 실제 기기의 Flutter 앱에서 작동하지 않습니다.

분류에서Dev

Flutter / Dart : Widget Param에서 int를 double로 캐스트가 작동하지 않습니다.

분류에서Dev

컨테이너의 고정 높이가 Flutter에서 작동하지 않습니다.

분류에서Dev

mat-sidenav-content가 MatSidenavContainer에 대한 공급자를 던지지 않습니다.

분류에서Dev

multi Provider가 Flutter의 Material 앱에서 작동하지 않습니까?

분류에서Dev

Flutter에서 RaisedButton 클릭시 스낵바가 작동하지 않습니까?

Related 관련 기사

  1. 1

    View :: composer가 boot () 서비스 공급자에서 작동하지 않습니다.

  2. 2

    DotNetOpenAuth 공급자가 https의 IE11에서 작동하지 않습니다.

  3. 3

    Flutter Firestore getDocuments ()가 initState에서 작동하지 않습니다.

  4. 4

    setState ()가 flutter에서 제대로 작동하지 않습니다.

  5. 5

    Flutter Firebase Auth가 Google Play에서 작동하지 않습니다.

  6. 6

    Flutter hot reload가 VSCode의 자동 저장에서 작동하지 않습니다.

  7. 7

    EF 캐싱 공급자 래퍼가 EF 6.0.2에서 작동하지 않습니다.

  8. 8

    Flutter 제공자가 notifyListeners에 응답하지 않습니다

  9. 9

    Navigator.push가 flutter에서 setState와 함께 작동하지 않습니다.

  10. 10

    Flutter의 Align 위젯에서 onTap 함수가 작동하지 않습니다.

  11. 11

    Row ()의 컨테이너가 Flutter에서 작동하지 않습니다.

  12. 12

    Flutter의 PayPal WebView가 물리적 장치에서 작동하지 않습니다.

  13. 13

    Angular 2 공급자가 useValue 및 new에 대한 함수 호출과 함께 작동하지 않습니다.

  14. 14

    검색 사용자가 Flutter에서 작동하지 않습니다. 어떻게 해결합니까?

  15. 15

    Flutter async / await가 2 개의 Firebase 함수간에 작동하지 않습니다.

  16. 16

    StaggeredGridView의 동적 높이가 flutter 프로젝트에서 작동하지 않습니다.

  17. 17

    'flutter pub get'이 VSCode에서 작동하지 않습니다.

  18. 18

    Angular 8 Resolver가 작동하지 않음 : Resolver에 대한 공급자 없음

  19. 19

    Flutter 공급자가 UI를 업데이트하지 않음

  20. 20

    Flutter에서 List의 ADD 메서드가 작동하지 않습니다 (List.add ()).

  21. 21

    Dart / Flutter WebSocket 서버 / 클라이언트가 같은 쪽에서 제대로 작동하지 않습니다.

  22. 22

    Flutter TikTokStyleFullPageScroller ()가 비어있는 (콘텐츠가 아닌) 화면에서 작동하지 않습니다.

  23. 23

    C ++ 문자열에서 공백 제거가 작동하지 않습니다.

  24. 24

    Firebase Phone Auth가 iOS 시뮬레이터 나 실제 기기의 Flutter 앱에서 작동하지 않습니다.

  25. 25

    Flutter / Dart : Widget Param에서 int를 double로 캐스트가 작동하지 않습니다.

  26. 26

    컨테이너의 고정 높이가 Flutter에서 작동하지 않습니다.

  27. 27

    mat-sidenav-content가 MatSidenavContainer에 대한 공급자를 던지지 않습니다.

  28. 28

    multi Provider가 Flutter의 Material 앱에서 작동하지 않습니까?

  29. 29

    Flutter에서 RaisedButton 클릭시 스낵바가 작동하지 않습니까?

뜨겁다태그

보관