flutter 无法从一页导航到下一页(抖动)

nlejzf6q  于 2023-06-24  发布在  Flutter
关注(0)|答案(3)|浏览(150)

我是新的Flutter,我想从主导航. dart 到类别. dart 当我贴在一张卡片上我得到了一个错误说:使用不包括导航器的上下文请求导航器操作。这是密码main.dart

import 'package:bornmonth/Category.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    const appTitle = 'طالع بینی ماه تولد';

    return MaterialApp(

      builder: (context, child) {
        return Directionality(
          textDirection: TextDirection.rtl,
          child: Scaffold(
            appBar: AppBar(
              title: const Text(appTitle, style: TextStyle(color: MyColorsSample.primaryDark),),
              backgroundColor: Colors.white,
              elevation: 0,

              actions: [
                IconButton(onPressed: (){}, icon: const Icon(Icons.star_half, color: Colors.blueAccent,)),
                IconButton(onPressed: (){}, icon: const Icon(Icons.share, color: Colors.blueAccent,)),
                IconButton(onPressed: (){}, icon: const Icon(Icons.help, color: Colors.blueAccent,)),

              ],
            ),
            body:  const CardBasicRoute(),
          ),
        );
      },
        home:  const CardBasicRoute(),
    );
  }
}

double defaultRadius = 8.0;

class CardBasicRoute extends StatefulWidget {

  const CardBasicRoute({super.key});

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

class CardBasicRouteState extends State<CardBasicRoute> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(8),
        scrollDirection: Axis.vertical,
        child: Column(
          children: <Widget>[
            Container(height:5),

            gradientCardSample("حمل/فروردین", "من هستم","hamal.png",1),
            SizedBox(height: 10,),
            gradientCardSample("ثور/اردبیهشت", "همه چیز مال من است", "sawr.png", 2),
            SizedBox(height: 10,),
            gradientCardSample("جوزا/خرداد", "من فکر میکنم", "jawza.png", 3),
            SizedBox(height: 10,),
            gradientCardSample("سرطان/تیر", "من احساس میکنم", "saratan.png", 4),
            SizedBox(height: 10,),
            gradientCardSample("اسد/مرداد", "من اراده میکنم", "asad.png", 5),
            SizedBox(height: 10,),
            gradientCardSample("سنبله/شهریور", "من تجزیه و تحلیل میکنم", "sonbola.png", 6),
            SizedBox(height: 10,),
            gradientCardSample("میزان/مهر", "من تعادل را برقرار میکنم", "mizan.png", 7),
            SizedBox(height: 10,),
            gradientCardSample("عقرب/آبان", "من آرزو میکنم", "aqrab.png", 8),
            const SizedBox(height: 10,),
            gradientCardSample("قوس/دی", "من میبینم", "qaws.png", 9),
            SizedBox(height: 10,),
            gradientCardSample("جدی/دی", "من بکار میگیرم", "jadi.png", 10),
            SizedBox(height: 10,),
            gradientCardSample("دلو/بهمن", "من میدانم", "dalw.png", 11),
            SizedBox(height: 10,),
            gradientCardSample("حوت/اسفند", "من باور دارم", "hoot.png", 12),

          ],
        ),
      ),
    );
  }

  Widget gradientCardSample(String title, String subtitle, String image, int hint) {
    return InkWell(
      splashColor: Colors.black.withAlpha(30),
      onTap: () {
        debugPrint('Card tapped.');

          Navigator.of(context).push(MaterialPageRoute(builder: (context) => const Catgory()));

      },
      child: Container(
        height: 110,
        width: double.infinity,
        padding:  const EdgeInsets.all(10),
        decoration: BoxDecoration(
            gradient: const LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [ Color(0xFF846AFF), Color(0xFF755EE8), Colors.purpleAccent,Colors.pinkAccent,],
            ),
            borderRadius: radius(16)),
        clipBehavior: Clip.hardEdge,

        child: Row(

          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 10,),
                Text(title, style: const TextStyle(fontSize: 20, color: Colors.white, )),
                 Text(subtitle, style:const TextStyle(fontSize: 15, color: Colors.white, ))
              ],

            ),
            //, style: boldTextStyle(color: Colors.white, size: 20)
            const Spacer(),
            Align(
                alignment: Alignment.topLeft,
                child: Image(image: AssetImage('assets/images/$image'),height: 100, width: 100,)),
          ],

        ),

      ),
    );
  }

}

/// returns Radius
BorderRadius radius([double? radius]) {
  return BorderRadius.all(radiusCircular(radius ?? defaultRadius));
}
/// returns Radius
Radius radiusCircular([double? radius]) {
  return Radius.circular(radius ?? defaultRadius);
}



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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        // clipBehavior is necessary because, without it, the InkWell's animation
        // will extend beyond the rounded edges of the [Card] (see https://github.com/flutter/flutter/issues/109776)
        // This comes with a small performance cost, and you should not set [clipBehavior]
        // unless you need it.
        clipBehavior: Clip.hardEdge,
        child: InkWell(
          splashColor: Colors.blue.withAlpha(30),
          onTap: () {
            debugPrint('Card tapped.');
          },
          child: const SizedBox(
            width: double.infinity,
            height: 100,
            child: Center(
                child: Text('A card that can be tapped')
            ),
          ),
        ),
      ),
    );
  }
}

class NewScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('New Screen')),
      body: const Center(
        child: Text(
          'This is a new screen',
          style: TextStyle(fontSize: 24.0),
        ),
      ),
    );
  }
}

////////////////////////////////////////////////////////////////////////////////
/*Load image from folder assets/images/
 */
class ImgSample {
  static String get(String name){
    return 'assets/images/$name';
  }
}

class MyColorsSample {
  static const Color primary = Color(0xFF12376F);
  static const Color primaryDark = Color(0xFF0C44A3);
  static const Color primaryLight = Color(0xFF43A3F3);
  static const Color green = Colors.green;
  static Color black = const Color(0xFF000000);
  static const Color accent = Color(0xFFFF4081);
  static const Color accentDark = Color(0xFFF50057);
  static const Color accentLight = Color(0xFFFF80AB);
  static const Color grey_3 = Color(0xFFf7f7f7);
  static const Color grey_5 = Color(0xFFf2f2f2);
  static const Color grey_10 = Color(0xFFe6e6e6);
  static const Color grey_20 = Color(0xFFcccccc);
  static const Color grey_40 = Color(0xFF999999);
  static const Color grey_60 = Color(0xFF666666);
  static const Color grey_80 = Color(0xFF37474F);
  static const Color grey_90 = Color(0xFF263238);
  static const Color grey_95 = Color(0xFF1a1a1a);
  static const Color grey_100_ = Color(0xFF0d0d0d);
  static const Color transparent = Color(0x00f7f7f7);
}
class MyTextSample{

  static TextStyle? display4(BuildContext context){
    return Theme.of(context).textTheme.displayLarge;
  }

  static TextStyle? display3(BuildContext context){
    return Theme.of(context).textTheme.displayMedium;
  }

  static TextStyle? display2(BuildContext context){
    return Theme.of(context).textTheme.displaySmall;
  }

  static TextStyle? display1(BuildContext context){
    return Theme.of(context).textTheme.headlineMedium;
  }

  static TextStyle? headline(BuildContext context){
    return Theme.of(context).textTheme.headlineSmall;
  }

  static TextStyle? title(BuildContext context){
    return Theme.of(context).textTheme.titleLarge;
  }

  static TextStyle medium(BuildContext context){
    return Theme.of(context).textTheme.titleMedium!.copyWith(
      fontSize: 18,
    );
  }

  static TextStyle? subhead(BuildContext context){
    return Theme.of(context).textTheme.titleMedium;
  }

  static TextStyle? body2(BuildContext context){
    return Theme.of(context).textTheme.bodyLarge;
  }

  static TextStyle? body1(BuildContext context){
    return Theme.of(context).textTheme.bodyMedium;
  }

  static TextStyle? caption(BuildContext context){
    return Theme.of(context).textTheme.bodySmall;
  }

  static TextStyle? button(BuildContext context){
    return Theme.of(context).textTheme.labelLarge!.copyWith(
        letterSpacing: 1
    );
  }

  static TextStyle? subtitle(BuildContext context){
    return Theme.of(context).textTheme.titleSmall;
  }

  static TextStyle? overline(BuildContext context){
    return Theme.of(context).textTheme.labelSmall;
  }
}

类别.dart

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
            appBar: AppBar(
              title: const Text("کتگوری", style: TextStyle(color: MyColorsSample.primaryDark),),
              backgroundColor: Colors.white,
              elevation: 0,

            ),
            body: const category_card(),
          );
  }
}

class category_card extends StatefulWidget {
  const category_card({super.key});

  @override
  State<category_card> createState() => _category_cardState();
}

class _category_cardState extends State<category_card> {
  @override
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}


class MyColorsSample {
  static const Color primary = Color(0xFF12376F);
  static const Color primaryDark = Color(0xFF0C44A3);
  static const Color primaryLight = Color(0xFF43A3F3);
  static const Color green = Colors.green;
  static Color black = const Color(0xFF000000);
  static const Color accent = Color(0xFFFF4081);
  static const Color accentDark = Color(0xFFF50057);
  static const Color accentLight = Color(0xFFFF80AB);
  static const Color grey_3 = Color(0xFFf7f7f7);
  static const Color grey_5 = Color(0xFFf2f2f2);
  static const Color grey_10 = Color(0xFFe6e6e6);
  static const Color grey_20 = Color(0xFFcccccc);
  static const Color grey_40 = Color(0xFF999999);
  static const Color grey_60 = Color(0xFF666666);
  static const Color grey_80 = Color(0xFF37474F);
  static const Color grey_90 = Color(0xFF263238);
  static const Color grey_95 = Color(0xFF1a1a1a);
  static const Color grey_100_ = Color(0xFF0d0d0d);
  static const Color transparent = Color(0x00f7f7f7);
}

我尝试了这个问题,但仍然得到相同的错误https://stackoverflow.com/questions/50124355/flutter-navigator-not-working

kninwzqo

kninwzqo1#

您在中使用的上下文

Navigator.of(context).push(MaterialPageRoute(builder: (context) => const Catgory()));

引用StatefullWidget
需要传递构建方法上下文

zzwlnbp8

zzwlnbp82#

我发现你的代码有问题,你的代码应该像下面的代码一样写:

main.dart

import 'package:farhat/Category.dart';
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: CardBasicRoute(),
    );
  }
}

double defaultRadius = 8.0;

class CardBasicRoute extends StatefulWidget {
  const CardBasicRoute({super.key});

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

class CardBasicRouteState extends State<CardBasicRoute> {
  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        appBar: AppBar(
          title: const Text(
            'appTitle',
            style: TextStyle(color: MyColorsSample.primaryDark),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          actions: [
            IconButton(
                onPressed: () {},
                icon: const Icon(
                  Icons.star_half,
                  color: Colors.blueAccent,
                )),
            IconButton(
                onPressed: () {},
                icon: const Icon(
                  Icons.share,
                  color: Colors.blueAccent,
                )),
            IconButton(
                onPressed: () {},
                icon: const Icon(
                  Icons.help,
                  color: Colors.blueAccent,
                )),
          ],
        ),
        backgroundColor: Colors.white,
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(8),
          scrollDirection: Axis.vertical,
          child: Column(
            children: <Widget>[
              Container(height: 5),
              gradientCardSample("حمل/فروردین", "من هستم", "hamal.png", 1),
              SizedBox(
                height: 10,
              ),
              gradientCardSample(
                  "ثور/اردبیهشت", "همه چیز مال من است", "sawr.png", 2),
              SizedBox(
                height: 10,
              ),
              gradientCardSample("جوزا/خرداد", "من فکر میکنم", "jawza.png", 3),
              SizedBox(
                height: 10,
              ),
              gradientCardSample(
                  "سرطان/تیر", "من احساس میکنم", "saratan.png", 4),
              SizedBox(
                height: 10,
              ),
              gradientCardSample("اسد/مرداد", "من اراده میکنم", "asad.png", 5),
              SizedBox(
                height: 10,
              ),
              gradientCardSample(
                  "سنبله/شهریور", "من تجزیه و تحلیل میکنم", "sonbola.png", 6),
              SizedBox(
                height: 10,
              ),
              gradientCardSample(
                  "میزان/مهر", "من تعادل را برقرار میکنم", "mizan.png", 7),
              SizedBox(
                height: 10,
              ),
              gradientCardSample("عقرب/آبان", "من آرزو میکنم", "aqrab.png", 8),
              const SizedBox(
                height: 10,
              ),
              gradientCardSample("قوس/دی", "من میبینم", "qaws.png", 9),
              SizedBox(
                height: 10,
              ),
              gradientCardSample("جدی/دی", "من بکار میگیرم", "jadi.png", 10),
              SizedBox(
                height: 10,
              ),
              gradientCardSample("دلو/بهمن", "من میدانم", "dalw.png", 11),
              SizedBox(
                height: 10,
              ),
              gradientCardSample("حوت/اسفند", "من باور دارم", "hoot.png", 12),
            ],
          ),
        ),
      ),
    );
  }

  Widget gradientCardSample(
      String title, String subtitle, String image, int hint) {
    return InkWell(
      splashColor: Colors.black.withAlpha(30),
      onTap: () {
        debugPrint('Card tapped.');

        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => const CatgoryFaiz()));
      },
      child: Container(
        height: 110,
        width: double.infinity,
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
            gradient: const LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Color(0xFF846AFF),
                Color(0xFF755EE8),
                Colors.purpleAccent,
                Colors.pinkAccent,
              ],
            ),
            borderRadius: radius(16)),
        clipBehavior: Clip.hardEdge,
        child: Row(
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(
                  height: 10,
                ),
                Text(title,
                    style: const TextStyle(
                      fontSize: 20,
                      color: Colors.white,
                    )),
                Text(subtitle,
                    style: const TextStyle(
                      fontSize: 15,
                      color: Colors.white,
                    ))
              ],
            ),
            //, style: boldTextStyle(color: Colors.white, size: 20)
            const Spacer(),
            Align(
                alignment: Alignment.topLeft,
                child: Image(
                  image: AssetImage('assets/images/$image'),
                  height: 100,
                  width: 100,
                )),
          ],
        ),
      ),
    );
  }
}

/// returns Radius
BorderRadius radius([double? radius]) {
  return BorderRadius.all(radiusCircular(radius ?? defaultRadius));
}

/// returns Radius
Radius radiusCircular([double? radius]) {
  return Radius.circular(radius ?? defaultRadius);
}

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        // clipBehavior is necessary because, without it, the InkWell's animation
        // will extend beyond the rounded edges of the [Card] (see https://github.com/flutter/flutter/issues/109776)
        // This comes with a small performance cost, and you should not set [clipBehavior]
        // unless you need it.
        clipBehavior: Clip.hardEdge,
        child: InkWell(
          splashColor: Colors.blue.withAlpha(30),
          onTap: () {
            debugPrint('Card tapped.');
          },
          child: const SizedBox(
            width: double.infinity,
            height: 100,
            child: Center(child: Text('A card that can be tapped')),
          ),
        ),
      ),
    );
  }
}

class NewScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('New Screen')),
      body: const Center(
        child: Text(
          'This is a new screen',
          style: TextStyle(fontSize: 24.0),
        ),
      ),
    );
  }
}

////////////////////////////////////////////////////////////////////////////////
/*Load image from folder assets/images/
 */
class ImgSample {
  static String get(String name) {
    return 'assets/images/$name';
  }
}

class MyColorsSample {
  static const Color primary = Color(0xFF12376F);
  static const Color primaryDark = Color(0xFF0C44A3);
  static const Color primaryLight = Color(0xFF43A3F3);
  static const Color green = Colors.green;
  static Color black = const Color(0xFF000000);
  static const Color accent = Color(0xFFFF4081);
  static const Color accentDark = Color(0xFFF50057);
  static const Color accentLight = Color(0xFFFF80AB);
  static const Color grey_3 = Color(0xFFf7f7f7);
  static const Color grey_5 = Color(0xFFf2f2f2);
  static const Color grey_10 = Color(0xFFe6e6e6);
  static const Color grey_20 = Color(0xFFcccccc);
  static const Color grey_40 = Color(0xFF999999);
  static const Color grey_60 = Color(0xFF666666);
  static const Color grey_80 = Color(0xFF37474F);
  static const Color grey_90 = Color(0xFF263238);
  static const Color grey_95 = Color(0xFF1a1a1a);
  static const Color grey_100_ = Color(0xFF0d0d0d);
  static const Color transparent = Color(0x00f7f7f7);
}

class MyTextSample {
  static TextStyle? display4(BuildContext context) {
    return Theme.of(context).textTheme.displayLarge;
  }

  static TextStyle? display3(BuildContext context) {
    return Theme.of(context).textTheme.displayMedium;
  }

  static TextStyle? display2(BuildContext context) {
    return Theme.of(context).textTheme.displaySmall;
  }

  static TextStyle? display1(BuildContext context) {
    return Theme.of(context).textTheme.headlineMedium;
  }

  static TextStyle? headline(BuildContext context) {
    return Theme.of(context).textTheme.headlineSmall;
  }

  static TextStyle? title(BuildContext context) {
    return Theme.of(context).textTheme.titleLarge;
  }

  static TextStyle medium(BuildContext context) {
    return Theme.of(context).textTheme.titleMedium!.copyWith(
          fontSize: 18,
        );
  }

  static TextStyle? subhead(BuildContext context) {
    return Theme.of(context).textTheme.titleMedium;
  }

  static TextStyle? body2(BuildContext context) {
    return Theme.of(context).textTheme.bodyLarge;
  }

  static TextStyle? body1(BuildContext context) {
    return Theme.of(context).textTheme.bodyMedium;
  }

  static TextStyle? caption(BuildContext context) {
    return Theme.of(context).textTheme.bodySmall;
  }

  static TextStyle? button(BuildContext context) {
    return Theme.of(context).textTheme.labelLarge!.copyWith(letterSpacing: 1);
  }

  static TextStyle? subtitle(BuildContext context) {
    return Theme.of(context).textTheme.titleSmall;
  }

  static TextStyle? overline(BuildContext context) {
    return Theme.of(context).textTheme.labelSmall;
  }
}

您应该遵循此结构并单独编写void main()MaterialApp,而在这些类中不需要像下面的代码那样编写其他代码,并单独编写您的小部件。
示例:

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text(
      'Hello, World!',
      style: Theme.of(context).textTheme.headlineMedium,
    );
  }
}
4sup72z8

4sup72z83#

在方法中添加Buildcontext参数

Widget gradientCardSample(String title, String subtitle, String image, int hint,BuildContext context) {
        return InkWell(
          splashColor: Colors.black.withAlpha(30),
          onTap: () {
            debugPrint('Card tapped.');
    
              Navigator.of(context).push(MaterialPageRoute(builder: (context) => const Catgory()));
    
          },
          child: Container(
            height: 110,
            width: double.infinity,
            padding:  const EdgeInsets.all(10),
            decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [ Color(0xFF846AFF), Color(0xFF755EE8), Colors.purpleAccent,Colors.pinkAccent,],
                ),
                borderRadius: radius(16)),
            clipBehavior: Clip.hardEdge,
    
            child: Row(
    
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 10,),
                    Text(title, style: const TextStyle(fontSize: 20, color: Colors.white, )),
                     Text(subtitle, style:const TextStyle(fontSize: 15, color: Colors.white, ))
                  ],
    
                ),
                //, style: boldTextStyle(color: Colors.white, size: 20)
                const Spacer(),
                Align(
                    alignment: Alignment.topLeft,
                    child: Image(image: AssetImage('assets/images/$image'),height: 100, width: 100,)),
              ],
    
            ),
    
          ),
        );
      }
    
    }

相关问题