Android Studio 嗨,这是我的第一个Flutter项目,我试图打开用餐活动时,用户点击用餐按钮,但它没有发生

pn9klfpd  于 2023-06-24  发布在  Android
关注(0)|答案(2)|浏览(115)
import 'package:flutter/material.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  int _selectedButtonIndex = -1; // Track the index of the selected button

  bool _isSearchBarFocused = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(150.0),
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 6.0),
            child: AppBar(
              backgroundColor:  Color(0xff191919),
              shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(16.0),
                  bottomRight: Radius.circular(16.0),
                ),
              ),
              flexibleSpace: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 16.0),
                        child: Icon(
                          Icons.account_circle,
                          color: Color(0xffb3ff66),
                          size: 40,
                        ),
                      ),
                      SizedBox(width: 8.0),
                      Text(
                        'Restro Magic',
                        style: TextStyle(
                          fontSize: 20.0,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                          fontFamily: 'Montserrat',
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16.0),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16.0, 0.0 , 16.0, 10.0),
                    child: _buildAnimatedSearchBar(),
                  ),
                ],
              ),
            ),
          ),
        ),
        backgroundColor: Colors.white,
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Row(
                children: [
                  ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _selectedButtonIndex = 0; // Set the selected button index to 0 (Dine In)

                      });
                    },
                    style: ElevatedButton.styleFrom(
                      primary: _selectedButtonIndex == 0 ? Colors.lightGreen :Color(0xffb3ff66), // Highlight the button if selected
                      elevation: 4.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    child: const Text(
                      'Dine In',
                      style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                        fontFamily: 'Montserrat',
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _selectedButtonIndex = 1; // Set the selected button index to 1 (Takeaway)
                      });
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => DineIn()),

                      );
                    },
                    style: ElevatedButton.styleFrom(
                      primary: _selectedButtonIndex == 1 ? Colors.lightGreen : Color(0xffb3ff66), // Highlight the button if selected
                      elevation: 4.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    child: const Text(
                      'Takeaway',
                      style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                        fontFamily: 'Montserrat',
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _selectedButtonIndex = 2; // Set the selected button index to 2 (Delivery)
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      primary: _selectedButtonIndex == 2 ? Colors.lightGreen :Color(0xffb3ff66), // Highlight the button if selected
                      elevation: 4.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    child: const Text(
                      'Delivery',
                      style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                        fontFamily: 'Montserrat',
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _selectedButtonIndex = 3; // Set the selected button index to 3 (NC)
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      primary: _selectedButtonIndex == 3 ? Colors.lightGreen : Color(0xffb3ff66), // Highlight the button if selected
                      elevation: 4.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    child: const Text(
                      'NC',
                      style: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                        fontFamily: 'Montserrat',
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16.0),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                'Running Orders',
                style: TextStyle(
                  fontSize: 24.0,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            const SizedBox(height: 16.0),
            Expanded(
              child: ListView.builder(
                itemCount: 10, // Replace with actual number of orders
                itemBuilder: (context, index) {
                  return _buildOrderCard(
                    orderNumber: 'Order No. ${index + 1}',
                    customerName: 'Customer Name',
                    user: 'User',
                    tableNumber: 'Table No. T${index + 1}',
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAnimatedSearchBar() {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 400),
      margin: const EdgeInsets.only(bottom: 16.0),
      decoration: BoxDecoration(
        color: Color(0xffb3ff66),
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(
          color: Color(0xff696666),
          width: 2.0,
        ),
      ),
      child: TextFormField(
        style: const TextStyle(color: Colors.white),
        decoration: const InputDecoration(
          filled: true,
          fillColor: Color(0xff696666),
          hintText: 'Search your order',
          hintStyle: TextStyle(
            color: Colors.white70,
            fontFamily: 'Montserrat',
          ),
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(
            vertical: 12.0,
            horizontal: 16.0,
          ),
        ),
        onChanged: (value) {
          // Handle onChanged event
        },
        onTap: () {
          setState(() {
            _isSearchBarFocused = true;
          });
        },
        onEditingComplete: () {
          setState(() {
            _isSearchBarFocused = false;
          });
        },
      ),
    );
  }

  Widget _buildOrderCard({
    required String orderNumber,
    required String customerName,
    required String user,
    required String tableNumber,
  }) {
    return Card(
      color: Colors.white,
      shape: RoundedRectangleBorder(
        side: const BorderSide(color: Colors.black),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: ListTile(
        title: Text(
          orderNumber,
          style: const TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Customer Name: $customerName',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              'User: $user',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              tableNumber,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8.0),
            const LinearProgressIndicator(
              value: 0.5, // Replace with actual progress value
              backgroundColor: Color(0xffb3ff66),
              valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
            ),
          ],
        ),
      ),
    );
  }
}

class DineIn extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dine In'),
      ),
      body: Center(
        child: Text('Welcome to the Dine In screen!'),
      ),
    );
  }
}

push(context,MaterialPageRoute(builder:(context)=> DineIn(),);我还应用了这一行在用餐按钮代码,但仍然不工作,当我点击用餐,它不导航用餐活动,这是我的第一个项目在Flutter,我无法捕捉问题在这里.. thnx提前:)

bxjv4tth

bxjv4tth1#

首先,你把导航到DineIn页面上的外卖按钮。
其次,您将在控制台中看到一条错误消息,告诉您发生了什么错误:

Navigator operation requested with a context that does not include a Navigator.

通常,这将是MaterialApp的后代的上下文。但是您使用的上下文是在MaterialApp外部声明的build方法中的上下文。有两种方法可以解决。
一种是把MaterialApp抬到外面,把你的主

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

然后在构建中直接返回Scaffold,如

@override
  Widget build(BuildContext context) {
    return Scaffold(
    ...

另一种方法是在MaterialAppScaffold之间插入一个构建器,如下所示:

return MaterialApp(
      home: Builder(
        builder: (context) {
          return Scaffold(
          ...

这样,后面代码中引用的context就是Builder的子节点,它是MaterialApp的子节点

r7s23pms

r7s23pms2#

问题是您的Navigator正在使用MyApp的上下文,即MaterialApp的父级。
Navigator示例的创建是通过在小部件树中插入MaterialApp来完成的。在此之后,此类小部件的子部件可以访问和使用Navigator
为了解决这个问题,您应该将MaterialApp放在层次结构中更高的位置。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) => const MaterialApp(
        home: HomePage(),
      );
}

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

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

class _HomePageState extends State<HomePage> {
  int _selectedButtonIndex = -1; // Track the index of the selected button

  bool _isSearchBarFocused = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(150.0),
        child: Container(
          margin: const EdgeInsets.symmetric(vertical: 6.0),
          child: AppBar(
            backgroundColor: Color(0xff191919),
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(16.0),
                bottomRight: Radius.circular(16.0),
              ),
            ),
            flexibleSpace: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Row(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 16.0),
                      child: Icon(
                        Icons.account_circle,
                        color: Color(0xffb3ff66),
                        size: 40,
                      ),
                    ),
                    SizedBox(width: 8.0),
                    Text(
                      'Restro Magic',
                      style: TextStyle(
                        fontSize: 20.0,
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                        fontFamily: 'Montserrat',
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),
                Padding(
                  padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 10.0),
                  child: _buildAnimatedSearchBar(),
                ),
              ],
            ),
          ),
        ),
      ),
      backgroundColor: Colors.white,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _selectedButtonIndex =
                          0; // Set the selected button index to 0 (Dine In)
                    });
                  },
                  style: ElevatedButton.styleFrom(
                    primary: _selectedButtonIndex == 0
                        ? Colors.lightGreen
                        : Color(0xffb3ff66), // Highlight the button if selected
                    elevation: 4.0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  ),
                  child: const Text(
                    'Dine In',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'Montserrat',
                      fontSize: 16.0,
                    ),
                  ),
                ),
                const SizedBox(width: 8.0),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _selectedButtonIndex =
                          1; // Set the selected button index to 1 (Takeaway)
                    });
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => DineIn()),
                    );
                  },
                  style: ElevatedButton.styleFrom(
                    primary: _selectedButtonIndex == 1
                        ? Colors.lightGreen
                        : Color(0xffb3ff66), // Highlight the button if selected
                    elevation: 4.0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  ),
                  child: const Text(
                    'Takeaway',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'Montserrat',
                      fontSize: 16.0,
                    ),
                  ),
                ),
                const SizedBox(width: 8.0),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _selectedButtonIndex =
                          2; // Set the selected button index to 2 (Delivery)
                    });
                  },
                  style: ElevatedButton.styleFrom(
                    primary: _selectedButtonIndex == 2
                        ? Colors.lightGreen
                        : Color(0xffb3ff66), // Highlight the button if selected
                    elevation: 4.0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  ),
                  child: const Text(
                    'Delivery',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'Montserrat',
                      fontSize: 16.0,
                    ),
                  ),
                ),
                const SizedBox(width: 8.0),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _selectedButtonIndex =
                          3; // Set the selected button index to 3 (NC)
                    });
                  },
                  style: ElevatedButton.styleFrom(
                    primary: _selectedButtonIndex == 3
                        ? Colors.lightGreen
                        : Color(0xffb3ff66), // Highlight the button if selected
                    elevation: 4.0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  ),
                  child: const Text(
                    'NC',
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'Montserrat',
                      fontSize: 16.0,
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16.0),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.0),
            child: Text(
              'Running Orders',
              style: TextStyle(
                fontSize: 24.0,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          const SizedBox(height: 16.0),
          Expanded(
            child: ListView.builder(
              itemCount: 10, // Replace with actual number of orders
              itemBuilder: (context, index) {
                return _buildOrderCard(
                  orderNumber: 'Order No. ${index + 1}',
                  customerName: 'Customer Name',
                  user: 'User',
                  tableNumber: 'Table No. T${index + 1}',
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAnimatedSearchBar() {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 400),
      margin: const EdgeInsets.only(bottom: 16.0),
      decoration: BoxDecoration(
        color: Color(0xffb3ff66),
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(
          color: Color(0xff696666),
          width: 2.0,
        ),
      ),
      child: TextFormField(
        style: const TextStyle(color: Colors.white),
        decoration: const InputDecoration(
          filled: true,
          fillColor: Color(0xff696666),
          hintText: 'Search your order',
          hintStyle: TextStyle(
            color: Colors.white70,
            fontFamily: 'Montserrat',
          ),
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(
            vertical: 12.0,
            horizontal: 16.0,
          ),
        ),
        onChanged: (value) {
          // Handle onChanged event
        },
        onTap: () {
          setState(() {
            _isSearchBarFocused = true;
          });
        },
        onEditingComplete: () {
          setState(() {
            _isSearchBarFocused = false;
          });
        },
      ),
    );
  }

  Widget _buildOrderCard({
    required String orderNumber,
    required String customerName,
    required String user,
    required String tableNumber,
  }) {
    return Card(
      color: Colors.white,
      shape: RoundedRectangleBorder(
        side: const BorderSide(color: Colors.black),
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: ListTile(
        title: Text(
          orderNumber,
          style: const TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Customer Name: $customerName',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              'User: $user',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              tableNumber,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8.0),
            const LinearProgressIndicator(
              value: 0.5, // Replace with actual progress value
              backgroundColor: Color(0xffb3ff66),
              valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
            ),
          ],
        ),
      ),
    );
  }
}

class DineIn extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dine In'),
      ),
      body: Center(
        child: Text('Welcome to the Dine In screen!'),
      ),
    );
  }
}

相关问题