how to add new element to Slivers Flutter with changing the UI?

Issue

i need once the user click on send button. the text input field which he had add will be added to a list to be displayed inside the ListView. but the listView does NOT render the new element of the list. no change happen when the user click the send button!

The Code Is:

  Widget build(BuildContext context) {
    List<MessageModel> message = [
      MessageModel(
        isMine: false,
        messageBody: "receiver_message".tr,
        time: "message_time".tr,
      ),
      MessageModel(
        isMine: true,
        messageBody: "message_sender_body".tr,
        time: "message_time".tr,
      ),
    ];
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverFillRemaining(
            child: ListView.builder(
              itemCount: message.length,
              // physics: const BouncingScrollPhysics(),
              itemBuilder: (context, index) => MessageBody(
                isMine: message[index].isMine,
                messageBody: message[index].messageBody,
                time: message[index].time,
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: 
       TextField(
          controller: message_controller,
          onChanged: (value) {},
                suffixIcon: IconButton(
                  onPressed: () => setState(() {
                    var x=message_controller.text;
                    print("x $x");
                    message.add(
                      MessageModel(
                        isMine: true,
                        time: "message_time".tr,
                        messageBody: message_controller.text,
                      ),
                    );
                  }),
                  icon: const Icon(
                      Icons.arrow_forward_rounded,
                ),
              ),
        ),
      ),
    );
  }
}

Solution

From what I can see you should initialize the list of Messages outside the build method because every time the view is recreated, it will re-initialize it and you would only have those values ​​that you are passing at the beginning, otherwise I recommend that you also declare the message_controller and You initialize it in the initState so that when you try to access it, it does not return null, here is an adaptation that I made based on your code so that you try to understand a little better, the add function is in the floating button, I hope you be helpful



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

  late TextEditingController message_controller;
  List<String> message = ["aaa", "bbb"];

  @override
  void initState() {
    super.initState();
    message_controller = TextEditingController();
  }

  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          top: false,
          child: CustomScrollView(
            slivers: [
              SliverFillRemaining(
                child: SizedBox(
                  height: MediaQuery.of(context).size.height,
                  child: ListView.builder(
                    itemCount: message.length,
                    physics: const BouncingScrollPhysics(),
                    itemBuilder: (context, index) => Text(message[index]),
                  ),
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              var x = message_controller.text;
              message.add(x);
              print(message);
            });
          },
        ),
        bottomNavigationBar: Container(
          color: Colors.red,
          child: TextField(
              controller: message_controller,
              onChanged: (value) {
                IconButton(
                  onPressed: () => setState(() {
                    var x = message_controller.text;
                    print("x $x");
                    message.add(x);
                  }),
                  icon: const Icon(
                    Icons.arrow_forward_rounded,
                    color: Colors.blue,
                  ),
                );
              }),
        ));
  }
}

Answered By – Elvis Salabarria Aquino

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *