CRUD Write data logic – Fyne Golang GUI Tutorial 58

CRUD Write data logic – Fyne Golang GUI Tutorial 58

 

 


package main
// import fyne
import (
    "encoding/json"
    "io/ioutil"
    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/widget"
)
func main() {
    // student struct, you can use any name
    type Student struct {
        Name  string // name N is capital
        Phone string
    }
    // Now creat a slice/ array to store data
    var myStudentData []Student

    // new app
    a := app.New()
    // new title and window
    w := a.NewWindow("CRUD APP")
    // resize window
    w.Resize(fyne.NewSize(400, 400))
    // entry widget for name
    e_name := widget.NewEntry()
    e_name.SetPlaceHolder("Enter name here...")
    // entry widget for phone
    e_phone := widget.NewEntry()
    e_phone.SetPlaceHolder("Enter phone here...")
    // submit button
    submit_btn := widget.NewButton("Submit", func() {
        // logic part- store our data in json format
        // let create a struct for our data
        // Get data from entry widget and push to slice
        myData1 := &Student{
            Name:  e_name.Text, // data from name entry widget
            Phone: e_phone.Text,
        }
        // append / push data to our slice
        myStudentData = append(myStudentData, *myData1) // * star is very important
        // convert / parse data to json format
        // 3 arguments
        // 1st is our slice data
        // ignore 2nd
        // 3rd is identation, we are using space to indent our data
        final_data, _ := json.MarshalIndent(myStudentData, "", " ")
        // writing data to file
        // it take 3 things
        //file name .txt or .json or anything you want to use
        // data source, final_data in our case
        // writing/reading/execute permission
        ioutil.WriteFile("myFile_name.txt", final_data, 0644)
        /// we are done :)
        // lets test
        // empty input field after data insertion
        e_name.Text = ""
        e_phone.Text = ""
        // refresh name & phone entry object
        e_name.Refresh()
        e_phone.Refresh()
    })
    // show and run
    w.SetContent(
        // vbox container
        container.NewVBox(e_name, e_phone, submit_btn),
    )
    w.ShowAndRun()
}

Tony BB
 

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: