PageViewer 내의 위젯은 setState Flutter시 변경되지 않았습니다.

알룬

컨테이너를 탭할 때 페이지 뷰어 내부에서 위젯을 변경하려고했습니다. 그러나 컨테이너가 색상을 변경하지 않았고 인쇄 기능이 올바르게 작동합니다.

여기 내 PageViewer 코드

PageView.builder(
                  physics: NeverScrollableScrollPhysics(),
                  controller: _controller,
                  itemCount: _samplePages.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _samplePages[index % _samplePages.length];
                  },
                ),

그리고 여기 내 컨테이너 코드

Widget page2() {
Color containerColor = Colors.blue;
return Center(
  child: Padding(
    padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
    child: Container(
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(15)),
      child: Column(
        children: <Widget>[
          InkWell(
            onTap: () {
              setState(() {
                containerColor = Colors.red;
                print('changed');
              });
            },
            child: AnimatedContainer(
              width: 100,
              height: 100,
              color: containerColor,
              duration: Duration(seconds: 1),
            ),
          )
        ],
      ),
    ),
  ),
);

}

변경됨이 인쇄되지만 컨테이너 색상은 여전히 ​​파란색입니다. 누군가 내 실수가 어디 있는지 말해 줄 수 있습니까?

전에 감사합니다.

최신 정보:

여기 내 전체 코드 :

class _AddCustomerState extends State<AddCustomer> {


int currentPage = 1;

  Color containerColor = Colors.blue;
  bool isLoading = false;

  Widget page1() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Padding(
            padding: const EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Page 1')
               ],
            ),
          ),
        ),
      ),
    );
  }

  Widget page2() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Column(
            children: <Widget>[
              InkWell(
                onTap: () {
                  setState(() {
                    containerColor = Colors.red;
                    print('changed');
                  });
                },
                child: AnimatedContainer(
                  width: 100,
                  height: 100,
                  color: containerColor,
                  duration: Duration(seconds: 1),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget page3() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page4() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page5() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  List<Widget> _samplePages;

  @override
  void initState() {
    setState(() {
      _samplePages = [
              page1(),
              page2(),
              page3(),
              page4(),
              page5(),
            ];
    });
    super.initState();
  }

  final _controller = new PageController();
  static const _kDuration = const Duration(seconds: 1);
  static const _kCurve = Curves.ease;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: EdgeInsets.only(top: 50),
              child: Text(
                'ADD CUSTOMER',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(
              height: 30,
            ),
            AnimatedContainer(
              duration: Duration(milliseconds: 700),
              width: 600,
              height: currentPage == 4 ? 600 : 450,
              child: isLoading
                  ? SpinKitCircle(
                      size: 30,
                      color: Colors.white,
                    )
                  : PageView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _controller,
                      itemCount: _samplePages.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _samplePages[index % _samplePages.length];
                      },
                    ),
            ),
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 25.0),
              child: Container(
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        setState(() {
                          if (currentPage > 1) {
                            currentPage--;
                          }
                        });
                        _controller.previousPage(
                            duration: _kDuration, curve: _kCurve);
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(
                          currentPage == 1 ? 'Back' : 'Prev',
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                        )),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        _controller.nextPage(
                            duration: _kDuration, curve: _kCurve);
                        setState(() {
                          if (currentPage < 5) {
                            currentPage++;
                          }
                        });
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(currentPage > 4 ? 'Confirm' : 'Next',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18))),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
천흥 한

아래 실행 전체 코드를 붙여 복사 할 수 있습니다
당신의 필요를StatefulBuilder

작업 데모

여기에 이미지 설명 입력

코드 조각

 Widget page2() {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(15)),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      containerColor = Colors.red;
                      print('changed');
                    });
                  },
                  child: AnimatedContainer(
                    width: 100,
                    height: 100,
                    color: containerColor,
                    duration: Duration(seconds: 1),
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }

전체 코드

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AddCustomer(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @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:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class AddCustomer extends StatefulWidget {
  @override
  _AddCustomerState createState() => _AddCustomerState();
}

class _AddCustomerState extends State<AddCustomer> {
  int currentPage = 1;

  Color containerColor = Colors.blue;
  bool isLoading = false;

  Widget page1() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Padding(
            padding: const EdgeInsets.all(25.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[Text('Page 1')],
            ),
          ),
        ),
      ),
    );
  }

  Widget page2() {
    return StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(15)),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      containerColor = Colors.red;
                      print('changed');
                    });
                  },
                  child: AnimatedContainer(
                    width: 100,
                    height: 100,
                    color: containerColor,
                    duration: Duration(seconds: 1),
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget page3() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page4() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  Widget page5() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
        ),
      ),
    );
  }

  List<Widget> _samplePages;

  @override
  void initState() {
    setState(() {
      _samplePages = [
        page1(),
        page2(),
        page3(),
        page4(),
        page5(),
      ];
    });
    super.initState();
  }

  final _controller = new PageController();
  static const _kDuration = const Duration(seconds: 1);
  static const _kCurve = Curves.ease;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: EdgeInsets.only(top: 50),
              child: Text(
                'ADD CUSTOMER',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(
              height: 30,
            ),
            AnimatedContainer(
              duration: Duration(milliseconds: 700),
              width: 600,
              height: currentPage == 4 ? 600 : 450,
              child: isLoading
                  ? CircularProgressIndicator(
                      /* size: 30,
                color: Colors.white,*/
                      )
                  : PageView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _controller,
                      itemCount: _samplePages.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _samplePages[index % _samplePages.length];
                      },
                    ),
            ),
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 25.0),
              child: Container(
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        setState(() {
                          if (currentPage > 1) {
                            currentPage--;
                          }
                        });
                        _controller.previousPage(
                            duration: _kDuration, curve: _kCurve);
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(
                          currentPage == 1 ? 'Back' : 'Prev',
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 18),
                        )),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        _controller.nextPage(
                            duration: _kDuration, curve: _kCurve);
                        setState(() {
                          if (currentPage < 5) {
                            currentPage++;
                          }
                        });
                      },
                      child: Container(
                        height: 60,
                        width: 200,
                        child: Center(
                            child: Text(currentPage > 4 ? 'Confirm' : 'Next',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18))),
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(30)),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

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

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

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Flutter 이미지 위젯은 상태 변경시 업데이트되지 않습니다.

분류에서Dev

SetState ()를 호출 한 후 Flutter가 위젯을 다시 빌드하지 않음

분류에서Dev

'then'블록 안에 this.setState가 정의되지 않았습니다.

분류에서Dev

React this.setState가 정의되지 않았습니다.

분류에서Dev

데이터가 변경되지 않은 경우에도 setState를 사용하여 강제로 다시 렌더링 할 수 있습니까? 내 GUI가 업데이트되지 않습니까?

분류에서Dev

QListWidget은 사용자 정의 위젯 라벨을 표시하지 않습니다.

분류에서Dev

ActivityManager : 경고 : 활동이 시작되지 않았습니다. 현재 작업이 맨 앞으로 가져 왔습니다. 내가 읽은 모든 관련 답변은 유익하지 않았습니다.

분류에서Dev

Stateful 위젯을 생성 했는데도 setState () 함수가 정의되지 않은 이유는 무엇입니까?

분류에서Dev

Flutter : AnimatedSwitcher와 함께 setstate를 사용할 때 위젯이 다시 빌드되지 않음

분류에서Dev

지시문의 격리 된 범위 변수가 정의되지 않았습니다.

분류에서Dev

Flutter의 PageView 모듈 내에서 PageController가 제대로 설정되지 않았습니다. 비어 있지 않은 위치 오류 팝업

분류에서Dev

내 JK Flip-Flop의 시뮬레이션 출력은 아무것도 변경되지 않습니다.

분류에서Dev

VBA가 내 for 루프를 반복하지 않고 날짜 / 시간 형식이 변경되지 않았습니다.

분류에서Dev

로드시 JavaScript 변수가 정의되지 않았습니다.

분류에서Dev

setState 함수가 정의되지 않았습니다. 실룩 거리다

분류에서Dev

범위 값이 변경되었지만 시계가 실행되지 않았습니다.

분류에서Dev

Maven은 - 억제 [경고] JAR는 비어 있습니다 - 어떤 내용의 pom.xml에 포함 표시되지 않았다

분류에서Dev

Flutter 사용자 정의 위젯이 표시되지 않음

분류에서Dev

Flutter Wrap 위젯의 Text 위젯을 이전 위젯의 끝에서 시작하고 이전 위젯 아래에서 시작하지 않는 방법은 무엇입니까?

분류에서Dev

위젯에서 setState를 호출하여 다른 위젯으로 변경하는 방법은 무엇입니까?

분류에서Dev

위젯에서 setState를 호출하여 다른 위젯으로 변경하는 방법은 무엇입니까?

분류에서Dev

Flutter Unhandled 예외 : 비활성화 된 위젯의 조상을 찾는 것은 안전하지 않습니다.

분류에서Dev

Reactjs에서 setState () (후크 사용) 후에 정의되지 않았습니다.

분류에서Dev

포착되지 않은 참조 : 변수가 정의되지 않았습니다.

분류에서Dev

정의되지 않은 이름 '연락처'-Stateful 위젯의 Flutter toJson Map

분류에서Dev

정의되지 않은 setState 및 사용자 인증 오류입니다. .bind (this)를 시도했습니다. 시도한 fatpipe ... 작동하지 않습니다

분류에서Dev

Android 위젯은 데이터를 표시하지 않습니다.

분류에서Dev

Jekyll : Comments.app 위젯이 내 페이지에 표시되지 않습니다.

분류에서Dev

Flutter-버튼 내부의 텍스트가 변경되지 않습니다.

Related 관련 기사

  1. 1

    Flutter 이미지 위젯은 상태 변경시 업데이트되지 않습니다.

  2. 2

    SetState ()를 호출 한 후 Flutter가 위젯을 다시 빌드하지 않음

  3. 3

    'then'블록 안에 this.setState가 정의되지 않았습니다.

  4. 4

    React this.setState가 정의되지 않았습니다.

  5. 5

    데이터가 변경되지 않은 경우에도 setState를 사용하여 강제로 다시 렌더링 할 수 있습니까? 내 GUI가 업데이트되지 않습니까?

  6. 6

    QListWidget은 사용자 정의 위젯 라벨을 표시하지 않습니다.

  7. 7

    ActivityManager : 경고 : 활동이 시작되지 않았습니다. 현재 작업이 맨 앞으로 가져 왔습니다. 내가 읽은 모든 관련 답변은 유익하지 않았습니다.

  8. 8

    Stateful 위젯을 생성 했는데도 setState () 함수가 정의되지 않은 이유는 무엇입니까?

  9. 9

    Flutter : AnimatedSwitcher와 함께 setstate를 사용할 때 위젯이 다시 빌드되지 않음

  10. 10

    지시문의 격리 된 범위 변수가 정의되지 않았습니다.

  11. 11

    Flutter의 PageView 모듈 내에서 PageController가 제대로 설정되지 않았습니다. 비어 있지 않은 위치 오류 팝업

  12. 12

    내 JK Flip-Flop의 시뮬레이션 출력은 아무것도 변경되지 않습니다.

  13. 13

    VBA가 내 for 루프를 반복하지 않고 날짜 / 시간 형식이 변경되지 않았습니다.

  14. 14

    로드시 JavaScript 변수가 정의되지 않았습니다.

  15. 15

    setState 함수가 정의되지 않았습니다. 실룩 거리다

  16. 16

    범위 값이 변경되었지만 시계가 실행되지 않았습니다.

  17. 17

    Maven은 - 억제 [경고] JAR는 비어 있습니다 - 어떤 내용의 pom.xml에 포함 표시되지 않았다

  18. 18

    Flutter 사용자 정의 위젯이 표시되지 않음

  19. 19

    Flutter Wrap 위젯의 Text 위젯을 이전 위젯의 끝에서 시작하고 이전 위젯 아래에서 시작하지 않는 방법은 무엇입니까?

  20. 20

    위젯에서 setState를 호출하여 다른 위젯으로 변경하는 방법은 무엇입니까?

  21. 21

    위젯에서 setState를 호출하여 다른 위젯으로 변경하는 방법은 무엇입니까?

  22. 22

    Flutter Unhandled 예외 : 비활성화 된 위젯의 조상을 찾는 것은 안전하지 않습니다.

  23. 23

    Reactjs에서 setState () (후크 사용) 후에 정의되지 않았습니다.

  24. 24

    포착되지 않은 참조 : 변수가 정의되지 않았습니다.

  25. 25

    정의되지 않은 이름 '연락처'-Stateful 위젯의 Flutter toJson Map

  26. 26

    정의되지 않은 setState 및 사용자 인증 오류입니다. .bind (this)를 시도했습니다. 시도한 fatpipe ... 작동하지 않습니다

  27. 27

    Android 위젯은 데이터를 표시하지 않습니다.

  28. 28

    Jekyll : Comments.app 위젯이 내 페이지에 표시되지 않습니다.

  29. 29

    Flutter-버튼 내부의 텍스트가 변경되지 않습니다.

뜨겁다태그

보관