I'm receiving this error when running my flutter web, unexpected null value and when I look at my terminal it directs me to my main.dart where I'm being told that the error is coming from my Material widget.
Whereas I'm not understanding what's causing the error.
The following TypeErrorImpl was thrown building Builder:
Unexpected null value.
The relevant error-causing widget was:
Material Material
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:bwamnewsappadmin/pages/home.dart';
import 'package:bwamnewsappadmin/pages/sign_in.dart';
import 'package:provider/provider.dart';
import 'blocs/admin_bloc.dart';
import 'blocs/notification_bloc.dart';
import 'blocs/comment_bloc.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MultiProvider(providers: [
ChangeNotifierProvider<AdminBloc>(create: (context) => AdminBloc()),
ChangeNotifierProvider<CommentBloc>(create: (context) => CommentBloc()),
ChangeNotifierProvider<NotificationBloc>(create: (context) => NotificationBloc())
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
scrollBehavior: TouchAndMouseScrollBehavior(),
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
textTheme: GoogleFonts.poppinsTextTheme(),
appBarTheme: AppBarTheme(
color: Colors.white,
titleTextStyle: GoogleFonts.poppins(
color: Colors.grey[900],fontWeight: FontWeight.w600, fontSize: 18
),
elevation: 0,
actionsIconTheme: IconThemeData(
color: Colors.grey[900],
),
iconTheme: IconThemeData(
color: Colors.grey[900]
)
),
),
home: MyApp1(),
),
);
}
}
class MyApp1 extends StatelessWidget {
const MyApp1({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final ab = context.watch<AdminBloc>();
return ab.isSignedIn == false ? SignInPage() : HomePage();
}
}
class TouchAndMouseScrollBehavior extends MaterialScrollBehavior {
// Override behavior methods and getters like dragDevices
#override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
// etc.
};
}
Related
Error:- Unhandled Exception: PlatformException(invalid_sound, The resource notification could not be found. Please make sure it has been added as a raw resource to your Android head project., null, null)
I am trying a lot but every time got different errors, how I learn about local notification, please suggest something as an example.
Main class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'noti.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
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,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState(){
super.initState();
Notifications.initialize(flutterLocalNotificationsPlugin);
}
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFF3ac3cb), Color(0xFFf85187)])),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
backgroundColor: Colors.blue.withOpacity(0.5),
),
body: Center(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20)
),
width: 200,
height: 80,
child: ElevatedButton(
onPressed: (){
Notifications.showBigTextNotification(title: "New message title", body: "Your long body", fln: flutterLocalNotificationsPlugin);
}, child: Text("click"),
),
),
)),
);
}
}
Notification Class
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class Notifications{
static Future initialize(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
var androidInitialize = new AndroidInitializationSettings('mipmap/ic_launcher');
//var iOSInitialize = IOSInitializationSettings();
var initializationsSettings = new InitializationSettings(android: androidInitialize,
//iOS: iOSInitialize
);
await flutterLocalNotificationsPlugin.initialize(initializationsSettings );
}
static Future showBigTextNotification({var id =0,required String title, required String body,
var payload, required FlutterLocalNotificationsPlugin fln
} ) async {
AndroidNotificationDetails androidPlatformChannelSpecifics =
new AndroidNotificationDetails(
'2',
'channel_name',
playSound: true,
sound: RawResourceAndroidNotificationSound('notification'),
importance: Importance.max,
priority: Priority.high,
);
var not= NotificationDetails(android: androidPlatformChannelSpecifics,
//iOS: IOSNotificationDetails()
);
await fln.show(0, title, body,not );
}
}
When I run my flutter app for in iOS (both emulator and physical device), the app is displayed with huge padding from top and bottom. This only happens in iOS, the same app for android runs fine with the normal usual layout. All the app here is limited to this area in the display. I didn't define any padding for app in the code. What is the reason for this?
Here's the code in relevant screen;
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:instagram_clone_flutter/screens/register_screen.dart';
import 'package:instagram_clone_flutter/screens/signup_screen.dart';
import 'package:instagram_clone_flutter/utils/colors.dart';
import 'package:instagram_clone_flutter/utils/global_variable.dart';
import 'package:instagram_clone_flutter/widgets/post_card.dart';
class FeedScreen extends StatefulWidget {
const FeedScreen({Key? key}) : super(key: key);
#override
State<FeedScreen> createState() => _FeedScreenState();
}
class _FeedScreenState extends State<FeedScreen> {
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor:
width > webScreenSize ? webBackgroundColor : mobileBackgroundColor,
appBar: width > webScreenSize
? null
: AppBar(
backgroundColor: mobileBackgroundColor,
centerTitle: false,
title: Text("Iron Capital"),
/*SvgPicture.asset(
'assets/ic_instagram.svg',
color: primaryColor,
height: 32,
),*/
actions: [
IconButton(
icon: const Icon(
Icons.person_add_alt_1_sharp,
color: primaryColor,
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const RegisterScreen(),
),
);
},
),
],
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('posts').snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (ctx, index) => Container(
margin: EdgeInsets.symmetric(
horizontal: width > webScreenSize ? width * 0.3 : 0,
vertical: width > webScreenSize ? 15 : 0,
),
child: PostCard(
snap: snapshot.data!.docs[index].data(),
),
),
);
},
),
);
}
}
here's the main.dart file;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:instagram_clone_flutter/providers/user_provider.dart';
import 'package:instagram_clone_flutter/responsive/mobile_screen_layout.dart';
import 'package:instagram_clone_flutter/responsive/responsive_layout.dart';
import 'package:instagram_clone_flutter/responsive/web_screen_layout.dart';
import 'package:instagram_clone_flutter/screens/login_screen.dart';
import 'package:instagram_clone_flutter/utils/colors.dart';
import 'package:provider/provider.dart';
import 'package:instagram_clone_flutter/models/user.dart' as model;
import 'resources/auth_methods.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// initialise app based on platform- web or mobile
if (kIsWeb) {
await Firebase.initializeApp(
/* options: const FirebaseOptions(
apiKey: "AIzaSyCZ-xrXqD5D19Snauto-Fx_nLD7PLrBXGM",
appId: "1:585119731880:web:eca6e4b3c42a755cee329d",
messagingSenderId: "914283146786",
projectId: "instagram-clone-4cea4",
storageBucket: 'instagram-clone-4cea4.appspot.com'
),*/
);
} else {
await Firebase.initializeApp();
}
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => UserProvider(),),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Iron Capital',
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: mobileBackgroundColor,
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
// Checking if the snapshot has any data or not
if (snapshot.hasData) {
// final model.User user = Provider.of<UserProvider>(context).getUser;
//AuthMethods().signOut();
/*if(user.nft!.length < 2 ){
// await AuthMethods().signOut();
}*/
// if snapshot has data which means user is logged in then we check the width of screen and accordingly display the screen layout
return const ResponsiveLayout(
mobileScreenLayout: MobileScreenLayout(),
webScreenLayout: WebScreenLayout(),
);
} else if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
}
}
// means connection to future hasnt been made yet
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return const LoginScreen();
},
),
),
);
}
}
This is the problem that I got => The following assertion was thrown building CupertinoNavigationBarBackButton(dirty, dependencies: [_ModalScopeStatus]):
CupertinoNavigationBarBackButton should only be used in routes that can be popped
'package:flutter/src/cupertino/nav_bar.dart':
Failed assertion: line 1333 pos 9: 'currentRoute?.canPop == true'
I really do not understand this situation because I used previous 2 pages there is no problem but last page made problem.
Here is my related code part:(third page)
#override
Widget build(BuildContext context) {
final name = basename(widget.file!.path);
if(Platform.isIOS){
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: CupertinoNavigationBarBackButton(
color: CupertinoColors.white,
),
This is he way how to come here:
(first page)
CupertinoButton(
padding: EdgeInsets.all(0),
child: Icon(CupertinoIcons.list_bullet, color: CupertinoColors.white,),
onPressed: () => {
Navigator.push(context, CupertinoPageRoute(builder: (context) => ConsumptionReportsScreen(location: widget.location)))
}
),
(second page)
onTap: () async {
// final file = await PDFApi.loadNetwork(reports[index].pdfUrl);
const url = 'https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf';
final file = await PDFApi().loadNetwork(url);
Navigator.push(context, CupertinoPageRoute(builder: (context) => PdfViewerScreen(file: file)));
},
The error you're getting shows that the page you're currently on can't be popped.
Failed assertion: line 1333 pos 9: 'currentRoute?.canPop == true'
Are you sure there are pages in the stack that can be popped to?
first return a material app and in and inside it use CupertionoPageScaffold() as home page , i hope this will help
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
if(Platform.isIOS){
return MaterialApp(
home: CupertinoPageScaffold(
child: Container(),
),
);
}else {
return MaterialApp(
home: Scaffold(),
);
}
}
}
Try below code, I have try other way
CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
backgroundColor: CupertinoColors.activeGreen,
middle: const Text('Sample Code'),
leading: GestureDetector(
onTap: () {
print('Button Pressed');
Navigator.of(context).pop();
},
child: Icon(
CupertinoIcons.left_chevron,
color: CupertinoColors.white,
),
),
),
child: Container(),
),
Result screen->
I am new to Flutter and I wanted to have splash screen in my app. I used initState() and the navigator. But it didn't work. The app opens the splashscreen appears but after that it does not navigate to the next screen.
My main.dart
import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';
main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
#override
Widget build(BuildContext context) {
return SplashScreen();
}
}
class SplashScreen extends StatefulWidget{
#override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen>{
#override
void initState() {
super.initState();
Future.delayed(
Duration(
seconds: 4
),
(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
)
);
}
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0,
color: Colors.white,
fontWeight: FontWeight.bold
),
),
),
);
}
}
And my HomePage.dart
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
),
);
}
}
How can I resolve this?
Since I am new to flutter I dont know whether this is the right way to implement splashScreen if there are any other easier ways can you please suggest that also.
Thank you in advance.
Code Corrected:
MaterialApp should be the parent(root) of all Widgets.
import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: SplashScreen()); // define it once at root level.
}
}
class SplashScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0, color: Colors.white, fontWeight: FontWeight.bold),
),
);
}
}
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
);
}
}
The splash screen implementation is provided by default.
You just need to change the code in respective platforms like below
For Android:
Go to android directory in your flutter project and find the res folder where you will have launch_background.xml under drawables , just replace your own splash image as below.
`
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/white" />
<!-- You can insert your own image assets here -->
<item>
<bitmap
android:gravity="center"
android:src="#drawable/hotel_logo_new" />
</item>
</layer-list>
For iOS
- just change the LaunchImage under ImageAssets.
You should use pushReplacement instead of push when you exit the splash screen to prevent it from showing again when you press the back button.
here's the anmol.majhail code with the correct behavior.
import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: SplashScreen()); // define it once at root level.
}
}
class SplashScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}
class SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0, color: Colors.white, fontWeight: FontWeight.bold),
),
);
}
}
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
);
}
}
To use this package : add the dependency to your pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
splashscreen:
How to use
import 'package:flutter/material.dart';
import 'package:splashscreen/splashscreen.dart';
main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SplashScreen(
seconds: 10,
imageBackground: AssetImage('assets/images/a.jpg'),
navigateAfterSeconds: HomeScreen(),
),
); // define it once at root level.
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'Home',
style: new TextStyle(color: Colors.white),
),
),
);
}
}
Simple solution which i use in every app.
Use Timer class in build method code snippet
class SplashScreen extends StatefulWidget {
#override
Splash createState() => Splash();
}
class Splash extends State<SplashScreen> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
Timer(
Duration(seconds: 3),
() =>
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => LandingScreen())));
var assetsImage = new AssetImage(
'images/new_logo.png'); //<- Creates an object that fetches an image.
var image = new Image(
image: assetsImage,
height:300); //<- Creates a widget that displays an image.
return MaterialApp(
home: Scaffold(
/* appBar: AppBar(
title: Text("MyApp"),
backgroundColor:
Colors.blue, //<- background color to combine with the picture :-)
),*/
body: Container(
decoration: new BoxDecoration(color: Colors.white),
child: new Center(
child: image,
),
), //<- place where the image appears
),
);
}
}
Is it possible to display an iframe in Dart?
Below is the code that I am using
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final wordPair = WordPair.random();
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: Center(
child: Text(wordPair.asPascalCase), // With this highlighted text.
),
),
);
}
}
I am not sure how to add an iframe into this. Below is the snippet that is given in the documentation
factory IFrameElement() => JS(
'returns:IFrameElement;creates:IFrameElement;new:true',
'#.createElement(#)',
document,
"iframe");
I agree that using webview_flutter plugin shows HTML in Flutter. But, this plugin is currently supported in mobile but not yet for web. Here is an example of how you implement this on mobile:
Sample code using webview_flutter plugin:
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: WebView(
initialUrl: 'https://flutter.dev/',
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
javascriptMode: JavascriptMode.unrestricted,
),
);
}
}
Actual Output:
And regarding your question how to implement IFrameElement. There is actually an existing blog where it provides all the steps to understand this. But as mentioned, this is still in beta.
After I followed all the necessary steps, I've ended up in this example:
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'dart:html';
final 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: IframeDemo(),
),
),
);
}
}
class IframeDemo extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyWidget();
}
}
class MyWidget extends State<IframeDemo> {
String _url;
IFrameElement _iframeElement;
#override
initState() {
super.initState();
_url = 'https://flutter.dev/';
_iframeElement = IFrameElement()
..src = _url
..id = 'iframe'
..style.border = 'none';
//ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'iframeElement',
(int viewId) => _iframeElement,
);
}
#override
Widget build(BuildContext context) {
print('url is $_url');
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
),
SizedBox(
height: 600,
width: 600,
child: HtmlElementView(
viewType: 'iframeElement',
),
),
],
);
}
}
Sample Output: