使用 setState 或其他方式刷新 FutureBuilder

时间:2021-07-31 09:17:40

标签: android flutter dart tdlib

我在尝试刷新 FutureBuilder 中的 ListView 时遇到了问题,我无法刷新它,而不是使用 setState,而不是其他任何东西,对颤振有经验的人是否可以建议我使用 FutureBuilder 的方式有什么问题还是 setState?

这是我遇到问题的代码:

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  String contact_name;
  int contact_id;
  String str_id;
  List<Align> messagesList = [];
  Align messageUnit;
  int ownID;
  String ownName;
  double height;
  double width;
  final TextEditingController messageGetter = TextEditingController();


  @override
  void initState() {
    super.initState();
    final res = Variables.getContactName();
    contact_name = res;
    final res_2 = Variables.getContactID();
    contact_id = res_2;
    str_id = res_2.toString();
    final res_3 = Variables.getOwnID();
    ownID = res_3;
    final res_4 = Variables.getOwnName();
    ownName = res_4;
  }



  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future:getMessages(),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.hasData) {
            final data = snapshot.data;
            width = MediaQuery
                .of(context)
                .size
                .width;
            height = MediaQuery
                .of(context)
                .size
                .height;
            print(data);
            return Scaffold(
                appBar:
                AppBar(
                  title: Text(contact_name),
                  backgroundColor: Color(0xD3232323),
                ),
                body:
                Column(
                  children: [
                    Expanded(
                      child: ListView(
                        children: messagesList,
                        reverse: true,
                      ),
                    ),

                    Container(
                      child: Row(
                        children: [
                          Expanded(
                            child: Padding(
                              child: TextField(
                                controller: messageGetter,
                                decoration: InputDecoration(
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(20.0),
                                    borderSide: BorderSide(),
                                  ),
                                ),
                              ),
                              padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
                            ),
                          ),
                          Container(
                            child: Padding(
                              child: OutlinedButton(
                                onPressed: () {
                                  sendMessage();
                                  setState(() {
                                    getMessages();
                                  });
                                },
                                child: Text("+"),
                                style: ButtonStyle(
                                ),
                              ),
                              padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                )
            );
          }

          if (snapshot.hasError) {
            return Scaffold(
              appBar: AppBar(
                title: Text(contact_name),
                backgroundColor: Color(0xD3232323),
              ),
              body:
              Container(
                child:
                Align(alignment: Alignment.center,
                  child:
                  Text("Error"),
                ),
              ),
            );
          }

          if (snapshot.connectionState != ConnectionState.done) {
            return Scaffold(
              appBar: AppBar(
                title: Text(contact_name),
                backgroundColor: Color(0xD3232323),
              ),
              body:
              Container(
                child:
                Align(alignment: Alignment.center,
                  child:
                  CircularProgressIndicator(

                  ),
                ),
              ),
            );
          }

          else
            return Text("Meow");
        }
    );
  }

  Future<String> getMessages() async{
    final result = await context.read<TelegramService>().send(
      TdApi.GetChatHistory(chatId: contact_id, limit: 1, )
    );

    print(result);

    final res = await context.read<TelegramService>().send(
        TdApi.GetChatHistory(chatId: contact_id, limit: 999)
    );

    TdApi.Messages messages = res;

    messagesList.clear();

    for(var i = 0; i < messages.totalCount; i++) {

      TdApi.Message message = messages.messages[i];

      TdApi.MessageContent text = message.content;

      TdApi.MessageText textContent = text;

      TdApi.FormattedText textFinal = textContent.text;

      TdApi.MessageSenderUser messageSender = message.sender;

      if (messageSender.userId == ownID) {
        messageUnit = Align (
          alignment: Alignment.centerRight,
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
            child: OutlinedButton(
              child: Text(textFinal.text,
                style: TextStyle(
                  color: Color(0xD3232323),
                ),
              ),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Color(0xD300FFEA)),
              ),
            ),
          ),
        );
      }

      else {
        messageUnit = Align (
          alignment: Alignment.centerLeft,
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
            child: OutlinedButton(
              child: Text(textFinal.text),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Color(0xD3383838)),
              ),
            ),
          ),
        );
      }

      messagesList.add(messageUnit);
    }

    return "Messages Retrieved";
  }

  sendMessage() async {
    TdApi.FormattedText messageText = TdApi.FormattedText(text: messageGetter.text, entities: []);

    TdApi.MessageSendOptions messageSendOptions = TdApi.MessageSendOptions(disableNotification: false) ;

    TdApi.InputMessageText message = TdApi.InputMessageText(text: messageText);

    final result = await context.read<TelegramService>().send(
      TdApi.SendMessage(chatId: contact_id, inputMessageContent: message, options: messageSendOptions),
    );

    print(result);

    messageGetter.clear();

  }

}

1 个答案:

答案 0 :(得分:0)

用有状态的构建器包装你的列表视图,如下所示:

StatefulBuilder(builder: (context, setState) {
   return ListView(
     children: messagesList,
      reverse: true,);
    }),