android - 您如何在小部件中定义来自 future 的变量?

标签 android string flutter dart

这是我的代码:

import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MaterialApp(
      home: FirstScreen(),
    ));

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new Scaffold(
      appBar: new AppBar(
        centerTitle: true,
        title: new Text("My School Calendar"),
      ),
      body: Container(
          child: Align(
        alignment: Alignment(0, -0.9),
        child: FlatButton.icon(
          color: Colors.teal,
          icon: Icon(Icons.plus_one), //`Icon` to display
          label: Text('Create new entry'), //`Text` to display
          onPressed: () {
            Navigator.push(
              ctxt,
              new MaterialPageRoute(builder: (ctxt) => new SecondScreen()),
            );
          },
        ),
      )),
    );
  }
}

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  DateTime _date = new DateTime.now();
  TimeOfDay _time = new TimeOfDay.now();

  Future<Null> _selectDate(BuildContext ctxt) async {
    final DateTime picked = await showDatePicker(
      context: ctxt,
      initialDate: _date,
      firstDate: new DateTime.now().subtract(Duration(days: 1)),
      lastDate: new DateTime.now().add(Duration(days: 365)),
    );
    if (picked != null && picked != _date) {
      String oldDate = '${_date.toString()}';
      String newDate = oldDate.split(" ").first;
      print('Date selected: ' + newDate);
      setState((){
        _date = picked;
      });
    }
  }

  Future<Null> _selectTime(BuildContext ctxt) async {
    final TimeOfDay picked = await showTimePicker(
        context: ctxt,
        initialTime: _time
    );
    if (picked != null && picked != _time) {
      print('Date selected: ${_time.toString()}');
      setState((){
        _time = picked;
      });
    }
  }
  final myController = TextEditingController();
  @override
  Widget build(BuildContext ctxt) {
    return MaterialApp(
        home: Scaffold(
            appBar: new AppBar(
              title: new Text("Enter assignment details"),
            ),
            body: Container(
              margin: const EdgeInsets.only(top: 10.0),
              child: Align(
                alignment: Alignment(0, -0.9),
                child: Column(children: <Widget>[
                  TextField(
                    controller: myController,
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.black,
                          ),
                          borderRadius: BorderRadius.all(Radius.circular(15)),
                        ),
                        hintText: 'Enter assignment name'),
                  ),
                  FlatButton.icon(
                      color: Colors.redAccent,
                      icon: Icon(Icons.calendar_today), //`Icon` to display
                      label: Text('Select date'), //`Text` to display
                      onPressed: () {
                        _selectDate(ctxt);
                      }),
                  Text('Date selected: ' + newDate),
                  FlatButton.icon(
                      color: Colors.grey,
                      icon: Icon(Icons.access_time), //`Icon` to display
                      label: Text('Select time'), //`Text` to display
                      onPressed: () {
                        _selectTime(ctxt);
                      }),
                  Text('Time selected: ${_time.toString()}'),
                ]),
              ),
            )));
  }
}

在最底部我有代码 Text('Date selected: ' + newDate),. 然而,字符串“newDate”是未定义的,因为它在一个小部件中,但在未来被声明和定义。是否可以从 future 传输字符串“newDate”,以便它也可以在小部件中使用?我已经尝试了很多事情,比如试图在未来宣布,但他们都没有奏效。感谢您的帮助!

最佳答案

使用FutureBuilder 并将future 函数 作为FutureBuilderfuture 参数传递。

像这样:

   FutureBuilder(
      future: yourFuture(),
      builder: .....
     )

希望这对您有所帮助。

关于android - 您如何在小部件中定义来自 future 的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61624564/

相关文章:

PHP 从字符串中删除域名

java - SharedPreferences 如何与 UpdateUI 配合?

python - 打印 Python 程序的坐标

android - 在eclipse for android中构建路径错误

html - 为什么在提交表单后带引号的值被读取为空白?

ios - 使用 Flutter 插入 sqflite 时出现问题

android - Flutter & Firestore : app. INotificationSideChannel$Stub$Proxy 错误

flutter - 当启用空安全时,默认的 'List' 构造函数不可用。 flutter

java - 根据排序从 Arraylist 中删除对象

android - 如何解决拆分的 apk 和 bundle 的版本代码之间的冲突?