Home > Net >  Flutter complains about undefined var, however i defined it
Flutter complains about undefined var, however i defined it

Time:10-12

I created 2 pages, in first one i have TextField to pass data to second one. In second file i created class and Text class to output the phone number, but compiler says it's undefined. Both Class and Text() are in same dart file.

Class with constructor:

class ProfilePage extends StatefulWidget {
  final String phonenum;
  const ProfilePage({Key? key, required this.phonenum}) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

Text Class that must output name

Text(phonenum),

Function in first file to pass the phone number

void _submit() {
    Route route = MaterialPageRoute(builder: (context) => ProfilePage(phonenum: _phonenumber,));      // (constructors name: class member)
    Navigator.push(context, route);
  }

Page 1 code:

import 'package:flutter/material.dart';
import 'package:untitled/pages/ProfilePage.dart';
import 'package:untitled/pages/StadiumPage.dart';

void main() {
  runApp(LogInPage());
}

class LogInPage extends StatefulWidget {
  const LogInPage({Key? key}) : super(key: key);
  @override
  _LogInPageState createState() => _LogInPageState();
}

class _LogInPageState extends State<LogInPage> {
  String _phonenumber = '';

  @override
  Widget build(BuildContext context) {
    double _wid = MediaQuery.of(context).size.width;
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 180,
            ),
            Container(
              margin: EdgeInsets.only(left: 40),
              width: _wid,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'stadion.kg',
                    style: TextStyle(
                        fontSize: 35,
                        color: Colors.redAccent,
                        fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 20),
                  Text(
                    'Добро пожаловать!',
                    style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
                  ),
                  SizedBox(height: 50),
                  Text(
                    'Номер телефона:',
                    style: TextStyle(fontSize: 15, color: Colors.redAccent),
                  ),
                ],
              ),
            ),
            Padding(
                padding: EdgeInsets.symmetric(horizontal: 40),
                child: TextField(
                  keyboardType: TextInputType.phone,
                    onChanged: (value) {
                      _phonenumber = value;
                    },
                    maxLength: 9,
                    decoration: InputDecoration(
                        prefixIcon: Icon(Icons.phone), prefixText: ' 996'))),
            SizedBox(height: 45),
            ElevatedButton(
              onPressed: _submit,
              child: Text('Войти'),
              style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 140, vertical: 15),
                  primary: Colors.redAccent),
            ),
            SizedBox(height: 10),
            TextButton(
                onPressed: _submitnoregist,
                child: Text(
                  'Продолжить без регистрации!',
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: 16,
                      fontWeight: FontWeight.w400),
                ))
          ],
        ),
      ),
    );
  }

  void _submitnoregist() {
    Route route = MaterialPageRoute(builder: (context) => HomePage());      // (constructors name: class member)
    Navigator.push(context, route);
  }

  void _submit() {
    Route route = MaterialPageRoute(builder: (context) => ProfilePage(phonenum: _phonenumber,));      // (constructors name: class member)
    Navigator.push(context, route);
  }
}

Page 2 Code:

import 'package:flutter/material.dart';
import 'package:untitled/pages/FavoritesPage.dart';
import 'package:untitled/pages/MapPage.dart';
import 'package:untitled/pages/StadiumPage.dart';

class ProfilePage extends StatefulWidget {
  final String phonenum;
  const ProfilePage({Key? key, required this.phonenum}) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  int _selind = 0;

  List<Widget> _widgetopt = <Widget>[
    Text('Index 4'),
    Text('Index 2'),
    Text('Index 3'),
    Text('Index 4'),
  ];


  void OnBeingTapped(int index) {
    setState(() {
      _selind = index;
      if (index == 0) {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => HomePage()));
      } else if (index == 1) {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => MapPage()));
      } else if (index == 2) {
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => FavoritesPage()));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.indigo[50],
        appBar: AppBar(
          title: Text('Профиль', style: TextStyle(color: Colors.black)),
          backgroundColor: Colors.white,
          toolbarHeight: 80,
          centerTitle: true,
        ),
        body: Column(
          children: [
            SizedBox(
              height: 20,
            ),
            Center(
              child: Column(
                children: [
                  CircleAvatar(
                    backgroundImage: AssetImage('lib/assets/ava.jpg'),
                    maxRadius: 60,
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Text(
                    'Неизвестный\nпользователь',
                    style: TextStyle(fontWeight: FontWeight.w500, fontSize: 25),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(phonenum,
                      style: TextStyle(color: Colors.redAccent, fontSize: 20)),
                  SizedBox(
                    height: 10,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Container(
                      decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey,
                              blurRadius: 1.5,
                              offset: Offset(
                                1.5, // horizontal, move right 10
                                1.5, // vertical, move down 10
                              ),
                            )
                          ],
                          color: Colors.white,
                          border: Border.all(color: Colors.white70),
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: ButtonBar(
                        alignment: MainAxisAlignment.center,
                        children: [
                          SizedBox(
                            height: 30,
                          ),
                          TextButton(
                            onPressed: () {},
                            child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('Пользовательское соглашение',
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 20)),
                                  Icon(
                                    Icons.arrow_forward_ios_rounded,
                                    color: Colors.black,
                                  )
                                ]),
                          ),
                          TextButton(
                            onPressed: () {},
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('Пригласить друзей',
                                    style: TextStyle(
                                        color: Colors.black, fontSize: 20)),
                                Icon(
                                  Icons.arrow_forward_ios_rounded,
                                  color: Colors.black,
                                )
                              ],
                            ),
                          ),
                          TextButton(
                            onPressed: () {},
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('Выйти',
                                    style: TextStyle(
                                        color: Colors.black, fontSize: 20)),
                                Icon(
                                  Icons.arrow_forward_ios_rounded,
                                  color: Colors.black,
                                )
                              ],
                            ),
                          ),
                          SizedBox(
                            height: 30,
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
        bottomNavigationBar: SizedBox(
          height: 80,
          child: BottomNavigationBar(
            type: BottomNavigationBarType.fixed,
            backgroundColor: Colors.white,
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                  icon: Icon(
                    Icons.add_box_outlined,
                    color: Colors.black,
                  ),
                  label: ''),
              BottomNavigationBarItem(
                  icon: Icon(
                    Icons.location_on_outlined,
                    color: Colors.black,
                  ),
                  label: ''),
              BottomNavigationBarItem(
                  icon: Icon(
                    Icons.favorite_outline,
                    color: Colors.black,
                  ),
                  label: ''),
              BottomNavigationBarItem(
                  icon: Icon(
                    Icons.person_outline_outlined,
                    color: Colors.black,
                  ),
                  label: ''),
            ],
            currentIndex: _selind,
            selectedItemColor: Colors.yellow,
            onTap: OnBeingTapped,
          ),
        ),
      ),
      title: 'Stadium',
    );
  }
}

CodePudding user response:

phonenum is a class variable of ProfilePage and _ProfilePageState cannot access it directly. Because _ProfilePageState is a State class of ProfilePage you have a property called widget that you can use to access variables of ProfilePage class.

So your code should be like that:

Text(
  widget.phonenum,
  ...
  ...
)
  • Related