Splitting App into Widgets/Components - how to do it properly [duplicate] - flutter

This question already has answers here:
What is the difference between functions and classes to create reusable widgets?
(6 answers)
Closed 11 days ago.
I'm in the process of clean up my code in the mobile app.
I don't quite understand what is the difference between this code:
import 'package:flutter/material.dart';
class TestWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Row(
children: [
Text("test")
],
);
}
}
and this:
TestWidget(){
return Row(
children: [
Text("test")
],
);
}
I want to use later this components for example like this:
return MaterialApp(
home: TestWidget(),
);
I understand that it matters if the widget is stateful, but is it enough to create a function for such a component that will return the Widget, or should I wrap it in a stateless widget in some specific cases?

You can write it how ever you want but splitting the code helps you to understand better and clutter will be less

Related

can i return the GetBuilder in StatelessWidget build function directly?

some days ago, i raise an issue which link https://github.com/jonataslaw/getx/issues/2038#issue-1075353819
now i think there are something wrong in use getx ?
in my project i always return GetBuilder in build function, because my Scaffold has too many logic and state to use.
like this
class AppLogsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return GetBuilder<AppLogsLogic>(builder: (l) => Scaffold(
appBar: AppBar(
title: Text("app logs"),
),
// ... many logic and state use
),
);
}
}
but i saw the official document many times, it show me place the GetBuilder in the area where has some logic or state should be inject.
so i want to know it will make me face some problem? or not the best practice in Getx

How to Access a Variable that is Associated with other Widget in Flutter? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I need your Help Regarding an Issue that is Scratching my Head, Here I Got a Material Button, there is a Variable in it, that I want to Use in the Text Widget.
MaterialButton(
onPressed: () {
// My Random Code Goes Here. (Never Mind)
var currentEmoji = ...;
},
As you can see, I got a Material Button and Inside there is a big code, and the thing which I need to show you is the "currentEmoji" Variable.
I need to use this Variable in this Text Widget, which sits Just below this bit of Code,
child: Text(
*currentEmoji*,
textScaleFactor: 2,
),
I have a Material Button
I have an On Pressed Function in it.
In that Function there is a Variable currentEmoji
I want to Display this Variable inside the Text Widget
How to use currentEmoji Variable Outside the onPressed Function.
I want to Seek Your Help at this.
See below code,
class MyHomeActivity extends StatelessWidget {
// elements declared here can be used anywhere in this class
var currentEmoji;
#override
Widget build(BuildContext context) {
return Container(
child: MaterialButton(
onPressed: () {
// use currentEmoji here
},
),
);
}
}
No offence, but this is the basic concept of declaring variable globally, the common programming concept.
I encourage you to please go through the official docs of dart language here.
This will definitely ease you development journey.
Have a look at it in dartpad:
You need to declare the variable outside these two widgets, like so:
class _MyWidgetState extends State<MyWidget> {
String _currentEmoji = 'my initial emoji';
void _setEmoji() {
// My Random Code Goes Here. (Never Mind)
setState(() {
_currentEmoji = 'new emoji';
});
}
#override
Widget build(BuildContext context) {
return Column(children: [
ElevatedButton(
onPressed: _setEmoji,
child: Text('press me'),
),
Text(_currentEmoji),
]);
}
}

Locally overriding CupertinoTheme with Flutter

I'm working with Cupertino widgets, and need to locally override my global CupertinoTheme, and use CupertinoTheme widget for this purpose. My use case is to force some 'dark' theme when displaying text on top of images, but the issue is general.
In the following sample, I try to change the font size for one text style (from 42px to 21px), but it is not applied: the two texts have the same size (second should be 21px high).
It seems that CupertinoTheme.of(context) does not read the overriden style, contrary to the documentation
Descendant widgets can retrieve the current CupertinoThemeData by calling CupertinoTheme.of
Here is a sample (that can be tested on DartPad):
import 'package:flutter/cupertino.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoApp(
debugShowCheckedModeBanner: true,
theme: CupertinoThemeData(
brightness: Brightness.dark,
textTheme: CupertinoTextThemeData(
navLargeTitleTextStyle: TextStyle(fontSize: 42)
)
),
home: Home()
);
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Column(
children: [
Text(
'Hello, World #1!',
style: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
),
CupertinoTheme(
data: CupertinoThemeData(
textTheme: CupertinoTextThemeData(
navLargeTitleTextStyle: TextStyle(fontSize: 21)
)
),
child: Text(
'Hello, World #2!',
style:
CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
),
),
]
)
);
}
}
You’re getting the theme from the wrong context. The context must be a descendant of the CupertinoTheme widget (or rather the element that will be created from it). Try:
CupertinoTheme(
data: ...,
child: Builder(
builder: (context) => ... CupertinoTheme.of(contex)...
)
)
With the content parameter of the build method you can access anything done by ancestors of the build-method’s widget. Whatever you do in the build method has no effect on it.
Widgets are recipes for creating a tree of Elements. The context parameter that you get in build(er) method is (a reduced interface of) the element created for that widget. The Foo.of(context) methods typically search through the ancestor elements of context to find a Foo. (In some cases there is caching, so it isn’t a slow search.) When you create a tree of widgets in a build method, you’re just creating widgets; the elements will be created after that build method competes. Using a Builder widget, like I did above, delays creation of the widgets in Builder’s builder parameter until after an elements have been created for the Builder (and the widgets above it). So that is a way to get around your problem. Another way would be to create a new StatelessWidget with the widgets that are children of CupertinoTheme in your code, because it will similarly delay the creation of those widgets until after the element for that stateless widget (and its parents) is created.

Flutter responsive layout by enclosing everything in a root widget / How to change all double values of descendant widgets using one root widget

I was writing my own responsive layouts like this:
Instead of writing Normal code
Container(padding: EdgeInsets.all(10)),
Text("abc", style: TextStyle(fontSize: 20)),
I used a function responsiveSize()
Container(padding: EdgeInsets.all(responsiveSize(10, context))),
Text("abc", style: TextStyle(fontSize: responsiveSize(20, context))),
and define the function responsiveSize() as
double responsiveSize(double number, BuildContext context){
if (MediaQuery.of(context).size.width < 450) {
return number;
} else {
return number * 1.5;
}
}
or something like this which I can easily change.
But the problem with this is that I have to wrap every double value in my code with the function responsiveSize(), which is very tedious. I am looking for a way to wrap all my widgets in one root widget, like wrapping my MaterialApp widget inside a ResponsiveSize widget:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ResponsiveSize(
child: MaterialApp(
home: HomePage(),
),
);
}
}
and writing Normal code (as mentioned above, use double values as it is without wrapping them in a responsiveSize() function) and define ResponsiveSize widget in some way which I don't know. This way I can use responsive layout by just one widget and can easily remove the root ResponsiveSize widget if I don't want it later.
However this involves changing all double values in all descendant widgets of the ResponsiveSize widget, and this is something which I don't know how to do.
So, I would like to know how I can change all double values of all descendant widgets of a root widget? How should I define the root widget?
The LayoutBuilder widget might be what you're looking for.

How to properly implement math equations (TeX) in Flutter

I tried to implement math equations in flutter application using the flutter TeX package. It takes much time to render the equation.
It doesn't look so nice as I wanted to be. Are there any other implementations to effectively use math chemistry and other complex format equations without compromising the design.
here's my code:
import 'package:flutter/material.dart';
import 'package:flutter_tex/flutter_tex.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
body:TeXView(
teXHTML: r"""
<style>#myDiv
{color: "#CC0000",}</style>
<div id='myDiv'>$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$</div>
""" ,
renderingEngine: RenderingEngine.Katex, // Katex for fast render and MathJax for quality render.
onRenderFinished: (height) {
print("Widget Height is : $height");
},
onPageFinished: (string) {
print("Page Loading finished");
},
)
);
}}
Here's the output: [screenshot][1]
There is now also the catex package (full disclosure: I am an author).
CaTeX does not need web views, which is why you can render your equations extremely fast (basically as fast as any other widget).
Note: it is currently in pre-release, which means that a lot of functionality is still unsupported.
import 'package:catex/catex.dart';
Widget build(BuildContext context) => CaTeX(r'x = {-b \pm \frac{\sqrt{b^2-4ac}} {2a}}');
Just take a look at the latest version of flutter_tex:^3.5.0+2, styling feature has been added, now you can style each and everything very easily. There are some API changes in this version so please be careful before upgrading and do check the example before proceeding.
As for rendering speed is concerned you should change rendering engine from Mathjax to Katex which is much faster than Mathjax. e.g. renderingEngine:RenderingEngine.Katex