Home > other >  How to navigate to new page if the text widget is empty in flutter
How to navigate to new page if the text widget is empty in flutter

Time:08-31

Here in this following code I am using get method to display data from Api to my Text widget and everything is working fine, and then what I am trying to do is navigate to new page (i.e Login page)if the text widgets are empty (if get method doesn't work) so I have assigned a variable named 'textname' and checked if it is empty and if it is empty navigate to next page as shown in no.2 but my problem is it will navigate to new page even if it is not empty (no matter what the condition is it will always navigate to new page.)

 Positioned(
                    right: 130.0,
                    bottom: 20.0,
                    child: mapResponse == null
                        ? Container()
                        : textname = Text(
                            mapResponse!['ward_no'].toString(),
                            style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18.0),
                          ),
                  ),

void initState() {
getData();
super.initState();
Future.delayed(Duration.zero, () {
  if (textname?.isEmpty ?? true) {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => const Home()));

CodePudding user response:

Create new Function()

String PassData(String? data){
    Future.delayed(Duration.zero, () {
  if (textname?.isEmpty ?? true) {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => const Home()));
  return data;
}

Pass it in Your TextBox

 Text(PassData (mapResponse!['ward_no'].toString()),
                            style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 18.0),
                          ),

CodePudding user response:

initState is the first method to be started. Therefore, it is executed before the value is assigned to textname. You must assign a value in initState or check for null after assigning a value before that.

 Text? _textName = Text("First Page!!");

  @override
  void initState() {
    // TODO: implement initState
    if(_textName == null){
      Navigator.push(context, MaterialPageRoute(builder: (context) => SecondPage()));
    }
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned(
            right: 130.0,
            bottom: 20.0,
            child: _textName!,
            ),
        ],
      ),
    );
  }
  • Related