Flutter kIsWeb result being reversed/backward - flutter

i tried to check which platform that the app been used in flutter. followed this kIsWeb reference for checking it. this is the code that i used
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class ResponsiveLayout extends StatelessWidget {
final Widget mobileScreenLayout;
final Widget webScreenLayout;
const ResponsiveLayout({
Key? key,
required this.mobileScreenLayout,
required this.webScreenLayout,
}) : super(key: key);
#override
Widget build(BuildContext context) {
if (kIsWeb) {
//WEB SCREEN
return webScreenLayout;
}
//MOBILE SCREEN
return mobileScreenLayout;
}
}
the result was backward. when i run it on web it gave me the mobileScreenLayout and when i run it on emulator it gave me the webScreenLayout. tried to swap both webScreenLayout with the mobileScreenLayout and they work how supposedly with what i want. is there any problem with that or it's ok?
this the link i saw the kIsWeb
https://stackoverflow.com/a/57965689/18627424

Please check mobileScreenLayout and webScreenLayout. I think you added wrong text in these widgets by mistake. kIsWeb will definitely show web when you run it in web. You can also try
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text(
(kIsWeb)?'Hello World Web!':"hello world mobile",
style: Theme.of(context).textTheme.headline4,
);
}
}

Related

I'm having trouble with testing part while making flutter package

I want to develop a more advanced version of the ListView widget as a package. This is my first package.
I wrote a code like this:
modern_card_listview.dart:
library modern_card_listview;
import 'package:flutter/material.dart';
class CardListView extends StatefulWidget {
List items;
CardListView({Key? key, required this.items}) : super(key: key);
#override
State<CardListView> createState() => _CardListViewState();
}
class _CardListViewState extends State<CardListView> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: widget.items.length,
itemBuilder: ((context, index) {
return Card(
child: ListTile(
title: widget.items[index],
),
);
}),
),
),
);
}
}
I guess I need to use the dart file in the test folder to test the code.
modern_card_listview_test.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:modern_card_listview/modern_card_listview.dart';
CardListView _listView = CardListView(
items: const ["Bu bir", "Bu iki", "Bu uc", "Bu dort", "Bu bes"]);
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _listView,
),
);
}
}
How can I try the package I wrote? When I ran the code above, No tests were found. I get an error.This is my first pack and I'm still new. I would be grateful if you help.
I couldn't find a solution

How to display HTML text in Flutter in desktop

I want to display a paragraph in HTML that has various bold text and links within the tag using flutter on a desktop platform. I've come across "flutter_html", but the only supported platforms are for iOS and Android. Is there any other library that could display HTML text in a desktop environment? If there are none, are there any other ways to make this possible?
You can use flutter_html in desktop app.
Try my code below:
import 'package:html/dom.dart' as dom;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:html/parser.dart' show parse;
import 'package:flutter_html/flutter_html.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.yellow,
),
home: const HomePage(title: 'This Is Desktop'),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
HomePageState createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
#override
void initState() {
parseHtml();
super.initState();
}
Future<dom.Document> parseHtml() async {
return parse(await rootBundle.loadString('static/index.html'));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<dom.Document>(
future: parseHtml(),
builder:
(BuildContext context, AsyncSnapshot<dom.Document> snapshot) {
if (snapshot.hasData) {
return Html(data: snapshot.data?.outerHtml);
} else {
return const Center(
child: Text("Loading"),
);
}
}),
);
}
}
However, some tag has no effect. For example img tag not showing image, a tag only have link style but won't open a browser to a link when you click on it.
And some of css styles are not support, like flex.

Flutter web: get full screen size - not window size

My Flutter desktop web app has complex ui that would be too tricky to make responsive. So instead I want to put it in a FittedBox that will simply shrink the whole app if the user makes the browser window smaller.
class CustomPage extends StatelessWidget {
final Widget child;
const CustomPage({
Key? key,
required this.child,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: GetPlatform.isDesktop
? FittedBox(
child: SizedBox(
width: Get.width,
height: Get.height,
child: Center(child: child),
),
)
: Text('Sorry! This was only meant for desktop.'),
);
}
}
But Get.width and WidgetsBinding.instance.window.physicalSize.width only get the initial window size. So if the app is started in a full screen browser then this works great, but if the app is started in a small browser it doesn't work. MediaQuery.of(context).size.width only gets the current screen size.
Is there a way of getting a desktop physical screen size?
you need to import
import 'dart:html';
then window.screen?.width and window.screen?.height
will give you physycal screen size
import 'dart:html';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) => MaterialApp(debugShowCheckedModeBanner: false, home: Home());
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: LayoutBuilder(builder: (context, c) {
return Center(
child: Text('${window.screen?.width} ${window.screen?.height}'),
);
}),
);
}
}

How do I add Widgets to a Column through code

I'm trying to add widgets to a Column dynamically. The following approach does not work as the button does not add the text widgets when clicked. I'd like to understand why this doesn't work and what should I do to make it work. Thanks in advance for the help.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
List<Widget> c = [];
return MaterialApp(
title: 'Flutter Demo',
home: Column(children: [
Column(children: c),
ElevatedButton(onPressed: (){
print("testing");
c.add(Text("testing"));
}, child: Text("Add Text"))
])
);
}
}
Edit: I edited my code to be in a stateful widget and added a setState function around the function that adds the widgets to the container, but it still won't work
import 'package:flutter/material.dart';
class SW extends StatefulWidget {
const SW({ Key? key }) : super(key: key);
#override
_SWState createState() => _SWState();
}
class _SWState extends State<SW> {
#override
Widget build(BuildContext context) {
List<Widget> c = [];
return MaterialApp(
title: 'Flutter Demo',
home: Column(children: [
Column(children: c),
ElevatedButton(onPressed: (){
setState((){
print("testing");
c.add(Text("testing"));
});
},
child: Text("Add Text"))
])
);
}
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return SW();
}
}
void main() {
runApp(MyApp());
}
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home:MyApp()));
class MyApp extends StatefulWidget {
#override
_MyState createState() => _MyState();
}
class _MyState extends State<MyApp> {
List<Widget> c = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body:Column(children: [
Column(children: c),
ElevatedButton(onPressed: (){
setState((){
print("testing");
c.add(Text("testing"));
});
}, child: Text("Add Text"))
]),
);
}
}
Wrap your on pressed code in setstate to rebuild the page. The setState function triggers rebuild of the whole widget tree shown in your screen. And without that the text widget will only be added to the list but won't be shown to the screen.

Flutter: calling child class function from parent class of onother file

Question:
How to call methodA() from onPressed() of IconButton.
I've tryed to do this by using GlobalKey:
GlobalKey<_MyButtonState> globalKey = GlobalKey();
But it's returns an error.
I have read many forums on this and I have tried all the solutions posed but none of them are working for me.
CODE:
main.dart
import 'package:flutter/material.dart';
import 'button.dart';
void main() {
runApp(MaterialApp( title: 'My app', home: MyApp(),));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.help),
onPressed: () {
// how can I call methodA from here?
},
),
),
body: HomePage(),
),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Center(
child: MyButton(),
);
}
}
button.dart
import 'package:flutter/material.dart';
class MyButton extends StatefulWidget {
#override
_MyButtonState createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
#override
Widget build(BuildContext context) {
return Container( );
}
void methodA(){
print('methodA');
}
}
I have read many forums on this and I have tried all the solutions posed but none of them are working for me.
first, you will have to import the file as a package in main.dart:
Main.dart: (just writing the way to import the file)
import 'package:prioject_name/file_name.dart';
Note: this is for files under lib directory.
if your file is under a different directory inside lib
then add the path accordingly,
eg: Button.dart is inside the widgets folder inside the lib folder:
lib
|____widgets
|____Button.dart
then the import statement will be as follows:
import 'package:prioject_name/widgets/Button.dart';
Then try your global key method to call the function:
If it is still not working then you can use my method,
how I call methods from different class in onPressed or onTapped:
your Button.dart file.
import 'package:flutter/material.dart';
// changed the method definition class
class MyButton extends StatefulWidget {
void methodA(){
print('methodA');
}
#override
_MyButtonState createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
#override
Widget build(BuildContext context) {
...
widget.methodA(); // this would call the method A, anywhere inside the Widget build() function.
return Container( );
}
}
Now in Main.dart:
import 'package:prioject_name/Button.dart';
//call the function here using className().functioName();
....
onPressed(){
MyButton().methodA();
}
Take a look at the InheritedWidget class (and watch the videos).
Base class for widgets that efficiently propagate information down the
tree.
You can look at creating an InheritedWidget that contains a ValueNotifier.
class MyInheritedWidget extends InheritedWidget {
final ValueNotifier<int> buttonTapCountNotifier;
const MyInheritedWidget({
Key key,
#required this.buttonTapCountNotifier,
#required Widget child,
}) : assert(child != null),
super(key: key, child: child);
static MyInheritedWidget of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
}
}
Your MyButton class can call MyInheritedWidget.of(context).buttonTapCountNotifier to get hold of the ValueNotifier and add a listener to it.
Each time the ValueNotifier notifies your MyButton class that the value has been incremented, you can execute methodA.
You could use the Provider package which is quite the preferred method to manage state in Flutter apps. This will help you as well in organizing and growing the app in a clever way.
Take a look at the working code below.
define a ChangeNotifier (PressedProvider) which will save
current state of the app in a unique location and the behavior of your onPress function
you wrap your app
with a ChangeNotifierProvider widget
you wrap the receiving
Widget with a Consumer
you get the Provider.of() when you
need to do something and call a method on it
it will notify the Consumer of a change
Code:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(ChangeNotifierProvider<PressedProvider>( // 2
create: (_) => PressedProvider(),
child: MyApp(),
));
}
class PressedProvider extends ChangeNotifier { // 1
void pressButton() {
print("pressButton");
notifyListeners();
}
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
leading: Consumer<PressedProvider>( // 3
builder: (_, provider, widget) => IconButton(
icon: Icon(Icons.help),
onPressed: () {
provider.pressButton();
},
),
),
),
body: Center(
child: MyButton(),
),
),
);
}
}
class MyButton extends StatelessWidget {
#override
Widget build(BuildContext context) {
PressedProvider provider = Provider.of<PressedProvider>(context); // 4
return Center(
child: RawMaterialButton(
child: Text("Press me"),
onPressed: () => provider.pressButton()),
);
}
}