How do you define a variable from a future in a widget?

Viewed 290

This is my code:

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()}'),
                ]),
              ),
            )));
  }
}

On the very bottom I have the code Text('Date selected: ' + newDate),. However, the string "newDate" is undefined because it is in a widget but was declared and defined in a future. Is it possible to transfer the string "newDate" from the future so that it also works in the widget? I have tried many things such as trying to declare in it the future but they all haven't worked. Thanks for your help!

4 Answers

You have many options:

  1. You can make newDate a class variable and set it using setState(), then access that class field when you need it.

  2. You can use a FutureBuilder and get the value of a Future and use it there. If newDate is the return value from the Future, it will be available for the FutureBuilder.

Use a FutureBuilder and pass the future function as the future parameter of your FutureBuilder.

Like this:

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

Hope this helps.

The problem is: newDate is not getting updated because it isn't in setState

You can replace your Text to this

Text('Date selected: ${_date.day}/${_date.month}/${_date.year}'),

It works fine.

if you want to show date first import these

import 'package:intl/intl.dart';  //for date format
import 'package:intl/date_symbol_data_local.dart';

then declare variable

  var newDate=new DateFormat.yMMMd().format(new DateTime.now());

entire code is

import 'package:flutter/material.dart';

import 'package:intl/intl.dart'; //for date format
import 'package:intl/date_symbol_data_local.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
//**your variable
var newDate = new DateFormat.yMMMd().format(new DateTime.now());

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()}'),
                ]),
              ),
            )));
  }
}
Related