flutter -未正常调用函数

qxsslcnc  于 2023-02-16  发布在  Flutter
关注(0)|答案(1)|浏览(131)

我复制了我在YouTube上看的视频,制作了一个Edmob横幅广告。https://www.youtube.com/watch?v=NqorHLdqyV4在void initState()函数中写入super.initState(),但它在我的Android工作室中没有出现。

import 'dart:convert';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:app/count_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import './main.dart';


class HomePage extends StatelessWidget {
  HomePage({Key? key}) : super(key: key);
  final String androidTestId = 'ca-app-pub-3940256099942544/6300978111';
  late CountPage _countPage; BannerAd? banner;

  @override
  void initState() {
    super.initState();

    banner = BannerAd(
      listener: AdManagerBannerAdListener(),
      size: AdSize.banner,
      adUnitId: androidTestId,
      request: AdRequest(),
    )..load();
  }

  @override
  Widget build(BuildContext context) {
    _countPage = Provider.of<CountPage>(context, listen: true);

    List list = jsonDecode(_countPage.arrayText);
    bool toggle = false;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: _countPage.selection,
        title: Text('철학 한 스푼'),
        centerTitle: true, // 중앙 정렬
        elevation: 0.0,
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            UserAccountsDrawerHeader(
              // currentAccountPicture: CircleAvatar(
              //   backgroundImage: AssetImage('캡처.png'), // 앱 아이콘 들어갈자리
              //   backgroundColor: Colors.white,
              // ),
              accountName: Text('철학 한 스푼'),
              accountEmail: Text("개발자 이메일: kaingsik13@naver.com"),
              decoration: BoxDecoration(
                  color: _countPage.selection,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(40.0),
                    bottomRight: Radius.circular(40.0),
                  )),
            ),
            ListTile(
              leading: Icon(
                Icons.home,
                color: Colors.grey[850],
              ),
              title: Text('메인 화면'),
              onTap: () {
                print('메인 화면 확인');
              },
            ),
            ListTile(
              leading: Icon(
                Icons.settings,
                color: Colors.grey[850],
              ),
              title: Text('설정'),
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (BuildContext context) {
                      return Option_page();
                    }));
              },
            ),
            ListTile(
              leading: Icon(
                Icons.question_answer,
                color: Colors.grey[850],
              ),
              title: Text('리뷰 쓰기'),
              onTap: () {
                print('리뷰 화면 확인');
              },
            ),
            ListTile(
              leading: Icon(
                Icons.question_answer,
                color: Colors.grey[850],
              ),
              title: Text('후원 하기(광고 제거)'),
              onTap: () {
                print('후원 화면 확인');
              },
            ),
          ],
        ),
      ),
      body: Container(
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Center(
              child: IconButton(
                onPressed: () {
                  _countPage.page_down();
                },
                icon: Icon(Icons.chevron_left),
              ),
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: Container(
                      alignment: Alignment(0.0, 0.0),
                      color: Colors.white,
                      child: Text(
                        list[_countPage.page]["message"],
                        style: TextStyle(
                          fontSize: _countPage.font,
                          fontFamily: 'snow',
                        ),
                        textAlign: _countPage.align,
                      ),
                    ),
                  ),
                  Container(
                      height: 40,
                      width: 300,
                      color: Colors.white,
                      child: Center(
                          child: Text(
                            list[_countPage.page]["author"],
                            style: TextStyle(fontSize: 20, color: Colors.black),
                          ))),
                  Container(
                    child: AnimatedOpacity(
                      opacity: _countPage.visible ? 1.0 : 0.0,
                      duration: Duration(milliseconds: 500),
                      child: Container(
                          height: 50,
                          width: 70,
                          color: Colors.black38,
                          child: Center(
                              child: Text("복사 확인",
                                  style: TextStyle(
                                      fontSize: 15, color: Colors.white)))),
                    ),
                  ),
                ],
              ),
            ),
            Center(
                child: IconButton(
                    onPressed: () {
                      _countPage.page_up();
                    },
                    icon: Icon(Icons.chevron_right)))
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color:  _countPage.selection,
        child: Container(
          height: 150,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Center(
                      child: IconButton(
                          onPressed: () {
                            _countPage.copy_on();
                            Clipboard.setData(ClipboardData(
                                text: list[_countPage.page]["message"]));
                            Future.delayed(Duration(milliseconds: 800), () {
                              _countPage.copy_on();
                            });
                          },
                          icon: Icon(Icons.content_copy))),
                  Center(
                      child: IconButton(
                          onPressed: () {
                            Share.share(list[_countPage.page]["message"]);
                          },
                          icon: Icon(Icons.share))),
                ],
              ),
              Container(
                height: 100,
                color: Colors.green[50],
                child: this.banner == null
                ? Container()
                : AdWidget(
                    ad: this.banner!,
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }
}

强制超级初始化状态();我试过了,但是出现了错误。如果我的代码有问题,或者我提问的方式有任何改进,我希望你毫不犹豫地告诉我。我可以给你看我写的所有代码。

moiiocjp

moiiocjp1#

您正在使用StatelessWidget,但initState仅在StatefulWidgetState上可用
您的代码应该如下所示

import 'dart:convert';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:app/count_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import './main.dart';

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final String androidTestId = 'ca-app-pub-3940256099942544/6300978111';

  late CountPage _countPage; 
  BannerAd? banner;

  @override
  void initState() {
    super.initState();

    banner = BannerAd(
      listener: AdManagerBannerAdListener(),
      size: AdSize.banner,
      adUnitId: androidTestId,
      request: AdRequest(),
    )..load();
  }
  
  @override
  Widget build(BuildContext context) {
    _countPage = Provider.of<CountPage>(context, listen: true);

    List list = jsonDecode(_countPage.arrayText);
    bool toggle = false;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: _countPage.selection,
        title: Text('철학 한 스푼'),
        centerTitle: true, // 중앙 정렬
        elevation: 0.0,
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            UserAccountsDrawerHeader(
              // currentAccountPicture: CircleAvatar(
              //   backgroundImage: AssetImage('캡처.png'), // 앱 아이콘 들어갈자리
              //   backgroundColor: Colors.white,
              // ),
              accountName: Text('철학 한 스푼'),
              accountEmail: Text("개발자 이메일: kaingsik13@naver.com"),
              decoration: BoxDecoration(
                  color: _countPage.selection,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(40.0),
                    bottomRight: Radius.circular(40.0),
                  )),
            ),
            ListTile(
              leading: Icon(
                Icons.home,
                color: Colors.grey[850],
              ),
              title: Text('메인 화면'),
              onTap: () {
                print('메인 화면 확인');
              },
            ),
            ListTile(
              leading: Icon(
                Icons.settings,
                color: Colors.grey[850],
              ),
              title: Text('설정'),
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (BuildContext context) {
                      return Option_page();
                    }));
              },
            ),
            ListTile(
              leading: Icon(
                Icons.question_answer,
                color: Colors.grey[850],
              ),
              title: Text('리뷰 쓰기'),
              onTap: () {
                print('리뷰 화면 확인');
              },
            ),
            ListTile(
              leading: Icon(
                Icons.question_answer,
                color: Colors.grey[850],
              ),
              title: Text('후원 하기(광고 제거)'),
              onTap: () {
                print('후원 화면 확인');
              },
            ),
          ],
        ),
      ),
      body: Container(
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Center(
              child: IconButton(
                onPressed: () {
                  _countPage.page_down();
                },
                icon: Icon(Icons.chevron_left),
              ),
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: Container(
                      alignment: Alignment(0.0, 0.0),
                      color: Colors.white,
                      child: Text(
                        list[_countPage.page]["message"],
                        style: TextStyle(
                          fontSize: _countPage.font,
                          fontFamily: 'snow',
                        ),
                        textAlign: _countPage.align,
                      ),
                    ),
                  ),
                  Container(
                      height: 40,
                      width: 300,
                      color: Colors.white,
                      child: Center(
                          child: Text(
                            list[_countPage.page]["author"],
                            style: TextStyle(fontSize: 20, color: Colors.black),
                          ))),
                  Container(
                    child: AnimatedOpacity(
                      opacity: _countPage.visible ? 1.0 : 0.0,
                      duration: Duration(milliseconds: 500),
                      child: Container(
                          height: 50,
                          width: 70,
                          color: Colors.black38,
                          child: Center(
                              child: Text("복사 확인",
                                  style: TextStyle(
                                      fontSize: 15, color: Colors.white)))),
                    ),
                  ),
                ],
              ),
            ),
            Center(
                child: IconButton(
                    onPressed: () {
                      _countPage.page_up();
                    },
                    icon: Icon(Icons.chevron_right)))
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color:  _countPage.selection,
        child: Container(
          height: 150,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Center(
                      child: IconButton(
                          onPressed: () {
                            _countPage.copy_on();
                            Clipboard.setData(ClipboardData(
                                text: list[_countPage.page]["message"]));
                            Future.delayed(Duration(milliseconds: 800), () {
                              _countPage.copy_on();
                            });
                          },
                          icon: Icon(Icons.content_copy))),
                  Center(
                      child: IconButton(
                          onPressed: () {
                            Share.share(list[_countPage.page]["message"]);
                          },
                          icon: Icon(Icons.share))),
                ],
              ),
              Container(
                height: 100,
                color: Colors.green[50],
                child: this.banner == null
                    ? Container()
                    : AdWidget(
                  ad: this.banner!,
                ),
              ),

            ],
          ),
        ),
      ),
    );
  }
}

相关问题