How to call a variable or function from a different file to main.dart in flutter?

Viewed 42

I've been trying to implement a similar function like the NavigationBar widget in flutter. However, I don't want to use Icons instead I wanted to make a custom navbar with desired pics and everything was going well until I couldn't switch the middle section of my app (change different pages) when I tap/press the the textbutton.

You can check the UI here...crappy I know...am mimicking the till from my workplace...so the red section is the part I wanted to update when pressed

The side_buttons.dart file

import 'package:flutter/material.dart';
// ignore: unused_import
import 'package:timtill/main.dart';

class SideButtons extends StatefulWidget {
  final String text;
  final String imgUrl;

  const SideButtons({required this.text, required this.imgUrl});

  @override
  State<SideButtons> createState() => SideButtonsState();
}

class SideButtonsState extends State<SideButtons> {
//
  final List sideBtnLabels = [
    'HOT DRINKS',
    'COLD DRINKS',
    'DONUTS',
    'TIMBITS',
    'MUFFINS',
    'BAGELS',
    'SOUP',
    'LUNCH',
    'BREAK FAST',
    'BAKED',
    'TAKE-HOME',
    'Timmies'
  ];

  @override
  Widget build(BuildContext context) {
    return Transform.rotate(
      angle: -11,
      child: Container(
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFF9A9DAD), Color(0xFF4E4C56)])),
        height: 80,
        width: 80,
        child: TextButton(
            onPressed: () {
              int currentPageIndex = 0;

              int index = sideBtnLabels.indexOf(widget.text);
              setState(() {
                currentPageIndex = index;
              });

              int navMiddleIndex(int index) {
                return index;
              }

              print(sideBtnLabels.indexOf(widget.text));
              // print('index is changed to: ${navMiddleIndex(index).toString()}');
            },

            //////here Instead of text you can replace Node and import the dart:html
            //import 'dart:html';
            // text works because in the side_btn_page.dart we have specified the list of menu to it
            child: Stack(
              alignment: const AlignmentDirectional(0.0, 0.9),
              children: [
                Image.asset(
                  'imgs/' + widget.imgUrl,
                  //imgurl
                ),
                Text(
                  widget.text, //text
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                    foreground: Paint()
                      ..style = PaintingStyle.stroke
                      ..strokeWidth = 3
                      ..color = const Color.fromARGB(255, 63, 63, 63),
                  ),
                ),
                Text(
                  widget.text, //text
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFFEBEBEB),
                  ),
                ),
              ],
            )),
      ),
    );
  }
}

'''

The Main.dart file Note I wanted to update the currentPageIndex value from zero to the index number When I press the buttons please help me I'm beginner

import 'package:flutter/material.dart';
import 'package:timtill/pages/side_btn_page.dart';
import 'package:timtill/pages/middle_btn_page.dart';
import 'package:timtill/pages/middle_btn_page2.dart';
// ignore: unused_import
import 'package:timtill/util/side_buttons.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'TimsTill',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  int currentPageIndex = 0;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Column(
        children: [
          SizedBox(height: 80, child: SideButtonPage()),
          Expanded(
              flex: 12,
              child: Container(
                color: Colors.red,
                child: SizedBox(
                  width: MediaQuery.of(context).size.width,
                  child: Padding(
                    padding: const EdgeInsets.all(8),
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        child: <Widget>[
                          MiddleButtonPage(),
                          MiddleButtonPage2(),
                          Container(
                            color: Colors.green,
                            alignment: Alignment.center,
                            child: const Text('Page 2'),
                          ),
                          Container(
                            color: Colors.blue,
                            alignment: Alignment.center,
                            child: const Text('Page 3'),
                          ),
                        ][currentPageIndex],
                      ),
                    ),
                  ),
                ),
              )),
          Expanded(
              flex: 6,
              child: Container(
                color: Colors.purple,
              ))
        ],
      ),
    );
  }
}
1 Answers

First of all, you should implement a callback in your SideButtons widget, second, you should implement the defaultPageIndex. This way, SideButtons will return the selected index to its parent widget while maintening its state incase the widget try is rebuilt.

class SideButtons extends StatefulWidget {
final String text;
final String imgUrl;
final int defaultPageIndex;
final ValueChanged<int>? onChanged;
    
const SideButtons({required this.text, required this.imgUrl, this.defaultPageIndex = 0, this.onChanged});
    
      @override
      State<SideButtons> createState() => SideButtonsState();
    }
    
    class SideButtonsState extends State<SideButtons> {
    //
      final List sideBtnLabels = [
        'HOT DRINKS',
        'COLD DRINKS',
        'DONUTS',
        'TIMBITS',
        'MUFFINS',
        'BAGELS',
        'SOUP',
        'LUNCH',
        'BREAK FAST',
        'BAKED',
        'TAKE-HOME',
        'Timmies'
      ];
    
     late int currentPageIndex;
    
    @override
    initState(){
    currentPageIndex = defaultPageIndex;
    super.initState();
    }
    
      @override
      Widget build(BuildContext context) {
        return Transform.rotate(
          angle: -11,
          child: Container(
            decoration: const BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Color(0xFF9A9DAD), Color(0xFF4E4C56)])),
            height: 80,
            width: 80,
            child: TextButton(
                onPressed: () {
                 
    
                  int index = sideBtnLabels.indexOf(widget.text);
                  setState(() {
                    currentPageIndex = index;
  if( widget.onChanged != null)  widget.onChanged(index);
                  });
    
                  int navMiddleIndex(int index) {
                    return index;
                  }
    
                  print(sideBtnLabels.indexOf(widget.text));
                  // print('index is changed to: ${navMiddleIndex(index).toString()}');
                },
    
                //////here Instead of text you can replace Node and import the dart:html
                //import 'dart:html';
                // text works because in the side_btn_page.dart we have specified the list of menu to it
                child: Stack(
                  alignment: const AlignmentDirectional(0.0, 0.9),
                  children: [
                    Image.asset(
                      'imgs/' + widget.imgUrl,
                      //imgurl
                    ),
                    Text(
                      widget.text, //text
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                        foreground: Paint()
                          ..style = PaintingStyle.stroke
                          ..strokeWidth = 3
                          ..color = const Color.fromARGB(255, 63, 63, 63),
                      ),
                    ),
                    Text(
                      widget.text, //text
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFFEBEBEB),
                      ),
                    ),
                  ],
                )),
          ),
        );
      }
    }
Related